zoukankan      html  css  js  c++  java
  • B

    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 - 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);
    }
    
  • 相关阅读:
    PBR(基于物理的渲染)学习笔记
    iOS应用千万级架构开篇
    iOS应用千万级架构:性能优化与卡顿监控
    iOS应用千万级架构:自动埋点与曝光
    iOS应用千万级架构:存储持久化
    iOS应用千万级架构:MVVM框架
    Spring Boot入门系列(十七)整合Mybatis,创建自定义mapper 实现多表关联查询!
    Spring Boot入门系列(十六)使用pagehelper实现分页功能
    Spring Boot入门系列(十五)Spring Boot 开发环境热部署
    说迷茫
  • 原文地址:https://www.cnblogs.com/tomjobs/p/10617583.html
Copyright © 2011-2022 走看看