2017-10-07 16:15:16
writer;pprp
题目来源: Codility
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
一个长度为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
可以暴力求解:直接去做
代码如下:
/*
@theme:51nod 加农炮
@writer:pprp
@begin:16:00
@end:16:17
@declare:暴力求解
*/
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdiO>using namespace std;
int M, N;
int h[1000000];int main()
{freopen("in.txt","r",stdin);memset(h,0,sizeof(h));cin >> M >> N;int maxh = -100;for(int i = 0 ; i < M ; i++){cin >> h[i];if(maxh < h[i]){maxh = h[i];}}int cmp;for(int i = 0 ; i < N ; i++){cin >> cmp;if(cmp <= h[0] || cmp > maxh)continue;for(int j = 0 ; j < M ; j++){if(h[j] >= cmp){h[j-1]++;break;}}}for(int i = 0 ; i < M ; i++){cout << h[i] << endl;}return 0;
}
预处理,用lower_bound做
/*
@theme:51nod 加农炮
@writer:pprp
@begin:16:20
@end:
@declare:预处理
*/
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdiO>using namespace std;
int h[100000+10];
int canno[100000+10];
int M, N;int main()
{freopen("in.txt","r",stdin);cin >> M >> N;int maxh = -1000;for(int i = 0 ; i < M ; i++){cin >> h[i];maxh = max(maxh,h[i]);canno[i] = maxh;// 预处理
}int cmp;for(int i = 0 ; i < N ; i++){cin >> cmp;int j;if(cmp <= h[0] || cmp > maxh)continue;j = lower_bound(canno,canno+M,cmp)-canno;h[j-1]++;canno[j-1] = max(canno[j-1],h[j-1]);}for(int i = 0 ; i < M ; i++)cout << h[i] << endl;return 0;
}