[2018-3-16]BNUZ套题比赛div2 CodeForces 892B Wrath【补】

B. Wrath
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Hands that shed innocent blood!

There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li.

You are given lengths of the claws. You need to find the total number of alive people after the bell rings.

Input

The first line contains one integer n (1 ≤ n ≤ 106) — the number of guilty people.

Second line contains n space-separated integers L1, L2, ..., Ln (0 ≤ Li ≤ 109), where Li is the length of the i-th person's claw.

Output

Print one integer — the total number of alive people after the bell rings.

Examples
input
Copy
4
0 1 0 10
output
1
input
Copy
2
0 0
output
2
input
Copy
10
1 1 3 0 0 0 2 1 0 3
output
3
Note

In first sample the last person kills everyone in front of him.

题意:

        有n人,有一个Li长的爪子,可将此人前 Li 长的人都杀完,求最后存活的人数。

思路:

        首先, 我第一次做这题时,先想到了倒着遍历 最后一人绝对不会死的, 用一个数组去记人是否存活, 从后往前把死的人标出来最后记数, 我交了一次, 很明显 根据 1 ≤ n ≤ 106 ),数据量大,超时了。

        之后,仔细想想知道了一种更快的方法,依旧逆遍历,只要后一个能杀到的人前一个人的位置 就表示杀不到这个人计数器加一 就行。

代码:

TLE的:

#include <bits/stdc++.h>
#define N 1000010
using namespace std;

int n;

struct P{
	int len;
	bool alive;
} p[N];

int main() {
	while (~scanf("%d", &n)) {
		for (int i = 1; i <= n; i++) {
			scanf("%d", &p[i].len);
			p[i].alive = 1;
		}
		for (int i = n; i >= 2; i--) {
			if (p[i].len == 0)
				continue;
			int tmp;
			if (i - p[i].len <= 0) {
				tmp = 0;
			} else {
				tmp = i - p[i].len;
			}
			for (int j = i-1; j >= tmp; j--) {
				p[j].alive = 0;
			}
		}
		int cnt = 0;
		for (int i = 1; i <= n; i++) {
			if (p[i].alive)
				cnt++;
		}
		printf("%d\n", cnt);
	}
	return 0;
}
AC
#include <bits/stdc++.h>
#define N 1000010
using namespace std;

int n, p[N];

int main() {
	while (~scanf("%d", &n)) {
		for (int i = 1; i <= n; i++)
			scanf("%d", &p[i]);
			
		int tmp = n+1, cnt = 0;
		
		for (int i = n; i >= 1; i--) {
			if (i < tmp)
				cnt++;
			if (tmp >= i - p[i])
				tmp = i - p[i];
		}
		
		printf("%d\n", cnt);
	}
}


猜你喜欢

转载自blog.csdn.net/qq_40731186/article/details/79641206