New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell(i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.
Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to.
The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
8 4 1 2 1 2 1 2 1
YES
8 5 1 2 1 2 1 1 1
NO
In the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.
In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
题目大意:给一个数字n,一个数字t,n代表一排有n个房子(编号1~n),其中每个房子之间距离为1,t代表需要到达的房子,接着给你n-1个数字,存到数组a[i]里面,第i个房子能往后到达的距离为编号i加a[i](必须是这个距离),问能否从第一个房子到达指定的房子t。
代码如下:
#include <cstdio>
int main()
{
int n,m,a[30010];
scanf("%d%d", &n, &m);
int sum=1,flag=0;//flag标记是否能到达t那个房子 ,sum初始化为1
for(int i=1; i<n; i++)
{
scanf("%d",&a[i]);//输入第i个房子能往后到达的指定距离
}
int i=1;
while(i<n)
{
sum=sum+a[i];
i=sum;
if(i==m)//一旦到达了这个房子,那么标记一下,跳出
{
flag = 1;
break;
}
}
if(flag==1)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
return 0;
}