1.逛街
小Q在周末的时候和他的小伙伴来到大城市逛街,一条步行街上有很多高楼,共有n座高楼排成一行。
小Q从第一栋一直走到了最后一栋,小Q从来都没有见到这么多的楼,所以他想知道他在每栋楼的位置处能看到多少栋楼呢?(当前面的楼的高度大于等于后面的楼时,后面的楼将被挡住)
输入描述
输入第一行将包含一个数字n,代表楼的栋数,接下来的一行将包含n个数字wi(1<=i<=n),代表每一栋楼的高度。
1<=n<=100000;
1<=wi<=100000;
输出描述
输出一行,包含空格分割的n个数字vi,分别代表小Q在第i栋楼时能看到的楼的数量。
示例1
输入
6
5 3 8 3 2 5
输出
3 3 5 4 4 4
说明
当小Q处于位置3时,他可以向前看到位置2,1处的楼,向后看到位置4,6处的楼,加上第3栋楼,共可看到5栋楼。当小Q处于位置4时,他可以向前看到位置3处的楼,向后看到位置5,6处的楼,加上第4栋楼,共可看到4栋楼。
用一个单调栈,遍历两次
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> height(n);
for (int i = 0; i < n; ++i) {
cin >> height[i];
}
vector<int> ans(n, 0);
stack<int> stk;
for (int i = 0; i < n; i++)
{
while (!stk.empty() && height[stk.top()] <= height[i])
{
stk.pop();
ans[i]++;
}
stk.push(i);
ans[i] += stk.size();
}
while (!stk.empty()) stk.pop();
for (int i = n-1; i >= 0; i--)
{
while (!stk.empty() && height[stk.top()] <= height[i])
{
stk.pop();
ans[i]++;
}
stk.push(i);
ans[i] += stk.size();
}
for (int i = 0; i < n; ++i) {
--ans[i]; // delete repeated self(count twice)
cout << ans[i] << " ";
}
cout << endl;
return 0;
}
2.作者:Makki
链接:https://www.nowcoder.com/discuss/488619
来源:牛客网
小Q在进行射击气球的游戏,如果小Q在连续T枪中打爆了所有颜色的气球,将得到一只QQ公仔作为奖励。(每种颜色的气球至少被打爆一只)。这个游戏中有m种不同颜色的气球,编号1到m。小Q一共有n发子弹,然后连续开了n枪。小Q想知道在这n枪中,打爆所有颜色的气球最少用了连续几枪?
输入描述:
第一行两个空格间隔的整数数n,m。n<=1000000 m<=2000
第二行一共n个空格间隔的整数,分别表示每一枪打中的气球的颜色,0表示没打中任何颜色的气球。
输出描述:
一个整数表示小Q打爆所有颜色气球用的最少枪数。如果小Q无法在这n枪打爆所有颜色的气球,则输出-1
示例
输入:
12 5
2 5 3 1 3 2 4 1 0 5 4 3
输出:
6
test
12 5
2 5 3 1 3 2 4 1 5 0 4 3
5
解答: 和leetcode最小覆盖子串一模一样
#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <limits.h>
using namespace std;
int dfs(vector<int>& nums, int cnt)
{
unordered_map<int, int> m;
int len = nums.size();
int j = 0;
int sum = 0;
int maxlen = len;
for (int i = 1; i <= cnt; i++) m[i] = 1;
for (int i = 0; i < len; i++)
{
int c = nums[i];
m[c]--;
if (m[c] == 0) sum++;
while (sum == cnt)
{
if (i - j + 1 < maxlen) maxlen = i - j + 1;
m[nums[j]]++;
if (m[nums[j]] > 0) sum--;
j++;
}
}
return maxlen;
}
int main() {
int n;
int m;
while (cin >> n >> m)
{
vector<int> nums(n, 0);
for (int i = 0; i < n; i++) cin >> nums[i];
cout << dfs(nums, m) << endl;
}
return 0;
}