您的位置:首页 > 其它

51nod 1287加农炮【线段树*好题】

2017-10-19 22:07 393 查看
一个长度为M的正整数数组A,表示从左向右的地形高度。测试一种加农炮,炮弹平行于地面从左向右飞行,高度为H,如果某处地形的高度大于等于炮弹飞行的高度H(A[i] >= H),炮弹会被挡住并落在i - 1处,则A[i - 1] + 1。如果H <= A[0],则这个炮弹无效,如果H > 所有的A[i],这个炮弹也无效。现在给定N个整数的数组B代表炮弹高度,计算出最后地形的样子。
例如:地形高度A = {1, 2, 0, 4, 3, 2, 1, 5, 7}, 炮弹高度B = {2, 8, 0, 7, 6, 5, 3, 4, 5, 6, 5},最终得到的地形高度为:{2, 2, 2, 4, 3, 3, 5, 6, 7}。
Input
第1行:2个数M, N中间用空格分隔,分别为数组A和B的长度(1 <= m, n <= 50000)
第2至M + 1行:每行1个数,表示对应的地形高度(0 <= A[i] <= 1000000)。
第M + 2至N + M + 1行,每行1个数,表示炮弹的高度(0 <= B[i] <= 1000000)。

Output
输出共M行,每行一个数,对应最终的地形高度。

Input示例
9 11
1
2
0
4
3
2
1
5
7
2
8
0
7
6
5
3
4
5
6
5

Output示例
2
2
2
4
3
3
5
6
7


思路:

有点单调栈的意思,由于顺序结构,可以用线段树存储高度。/查找大于等于炮弹高度的下标,然后更新高度和dp数组。

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#define MAXN 1000010
using namespace std;
int dp[MAXN], high[MAXN];
int cnt;

void pushup(int root) {
dp[root] = max(dp[root<<1], dp[root<<1|1]);
}

void build(int root, int L, int R) {
if(R == L) {
scanf("%d", &dp[root]);
high[cnt++] = dp[root];
return;
}
int mid = (L + R) >> 1;
build(root<<1, L, mid);
build(root<<1|1, mid + 1, R);
pushup(root);
}

void updata(int root, int L, int R, int s) {
if(L == R) {
high[s]++;
dp[root]++;
return;
}
int mid = (L + R) >> 1;
if(s <= mid) updata(root<<1, L, mid, s);
else updata(root<<1|1, mid + 1, R, s);
pushup(root);
}

int query(int root, int L, int R, int s) {
if(L == R) {
if(s <= dp[root]) return L - 1;
else return L;
}
int mid = (L + R) >> 1;
int root1 = root<<1;
int root2 = root<<1|1;
if(dp[root1] >= s) {
query(root1, L, mid, s);
}
else {
query(root2, mid + 1, R, s);
}
}

int main() {
int n, m, k;
cnt = 1;
scanf("%d %d", &n, &m);
build(1, 1, n);
for(int i = 0; i < m; i++) {
scanf("%d", &k);
if(k <= high[1] || k > dp[1]) continue;
int ans = query(1, 1, n, k); //查找下标
updata(1, 1, n, ans); //更新树
}
for(int i = 1; i < cnt; i++) {
printf("%d\n", high[i]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: