Description
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.
思路
有一群人,给他们分别编号,当钟声响起,他们会用手里的刀杀人,给出了刀的长度,第i个人能杀第j个人的条件是:
j < i 且 j>=i-Li
所以我们利用RMQ或者线段树枚举从1到n之间的i-Li
的最小值,然后就可以判断这个人死不死,最后算出来死亡的总人数,再用总数减去就是答案
代码1(RMQ)
#include <cstdio>
#include <cstring>
#include <cctype>
#include <string>
#include <set>
#include <iostream>
#include <stack>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int N=1e6+20;
int a[N];
int minsum[N][20];
void RMQ(int num)
{
for(int j = 1; j < 20; ++j)
for(int i = 1; i <= num; ++i)
if(i + (1 << j) - 1 <= num)
{
minsum[i][j] = min(minsum[i][j - 1], minsum[i + (1 << (j - 1))][j - 1]);
}
}
int main()
{
int n,sum=0;
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
minsum[i][0]=i-a[i];
}
RMQ(n);
for(int i=1; i<n; i++)
{
int k=(int)(log(n-(i+1)+1.0)/log(2.0));
int minnum=min(minsum[i+1][k],minsum[n-(1<<k)+1][k]);
if(i>=minnum)sum++;
}
printf("%d\n",n-sum);
return 0;
}
代码2(线段树)
#include <cstdio>
#include <cstring>
#include <cctype>
#include <string>
#include <set>
#include <iostream>
#include <stack>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int N=1e6+20;
int a[N],b[N];
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int MIN[N<<2];
void pushup(int rt)
{
MIN[rt]=min(MIN[rt<<1],MIN[rt<<1|1]);
}
void build(int l,int r,int rt)
{
if(l==r)
{
MIN[rt]=b[l];
return;
}
int m=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}
int querymin(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
return MIN[rt];
int m=(l+r)>>1;
int ans=inf;
if(L<=m)
ans=min(ans,querymin(L,R,lson));
if(R>m)
ans=min(ans,querymin(L,R,rson));
return ans;
}
int main()
{
int n,sum=0;
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
b[i]=i-a[i];
}
build(1,n,1);
for(int i=1; i<n; i++)
{
int minnum=querymin(i+1,n,1,n,1);
if(i>=minnum)sum++;
}
printf("%d\n",n-sum);
return 0;
}