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.
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.
Print one integer — the total number of alive people after the bell rings.
4 0 1 0 10
1
2 0 0
2
10 1 1 3 0 0 0 2 1 0 3
3
In first sample the last person kills everyone in front of him.
题意:
有n人,有一个Li长的爪子,可将此人前 Li 长的人都杀完,求最后存活的人数。
思路:
首先, 我第一次做这题时,先想到了倒着遍历 最后一人绝对不会死的, 用一个数组去记人是否存活, 从后往前把死的人标出来最后记数, 我交了一次, 很明显 根据 n (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);
}
}