B - Wrath CodeForces - 892B(思维,水题)

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
4
0 1 0 10
Output
1
Input
2
0 0
Output
2
Input
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.

题意:排队,每个人可以杀死自己攻击范围内且在自己前面的人(被杀了还可以继续杀人),求活下来的人。
思路:一开始暴力,毫无悬念的超时了,看了下网上的代码,发现思路其实可以很优化,只要计算有多少人没有被攻击到即可。
注意:从后往前枚举,方便找到每个人的攻击范围
AC代码:

#include <bits/stdc++.h>
#define INF 1e9 + 5

using namespace std;
const int maxn = 1e6 + 5;
int len[maxn];

int main()
{
    int n;
    scanf("%d",&n);
    for(int i = 1;i <= n;i++)
    {
        scanf("%d",&len[i]);
    }
    int Maxx = INF;
    int ans = 0;
    for(int i = n;i >= 1;i--)
    {
        if(i >= Maxx)//打不到他
        {
            ans++;
        }
        Maxx = min(Maxx,i - len[i]);
    }
    printf("%d\n",n - ans);
    return 0;
}

暴力超时代码:

#include <bits/stdc++.h>//超时代码

using namespace std;
const int maxn = 1e6 + 5;
long long len[maxn];
long long is_alive[maxn];

int main()
{
    int n;
    scanf("%d",&n);
    for(int i = 0;i < n;i++)
    {
        scanf("%lld",&len[i]);
    }
    for(int i = 0;i < n;i++)
    {
        is_alive[i] = 1;
    }
    for(int i = n - 1;i >= 0;i--)
    {

                for(int k = i - 1;k >= i - len[i] && k >= 0;k--)
                {
                    is_alive[k] = 0;
                }

    }
    long long sum = 0;
    for(int i = 0;i < n;i++)
    {
        sum += is_alive[i];
    }
    printf("%lld",sum);
}

posted on 2019-03-28 14:28  tomjobs  阅读(193)  评论(0编辑  收藏  举报