E. Holes(分块)
题目链接:
Little Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:
There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai, then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions:
- Set the power of the hole a to value b.
- Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row.
Petya is not good at math, so, as you have already guessed, you are to perform all computations.
The first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types:
- 0 a b
- 1 a
For each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.
8 5
1 1 1 1 1 2 8 2
1 1
0 1 3
1 1
0 3 4
1 2
8 7
8 5
7 3
题意:从第i个洞可以到达i+power[i],0操作:power[x]=y,1操作询问从x跳出去一共跳了多少步,最后一个洞的编号;
思路:nex[i],num[i],last[i]表示从第i个洞跳到下一个块的洞的标号、跳的数目、和在次块的最后的洞的编号;
AC代码:
#include <bits/stdc++.h> using namespace std; const int maxn=1e5+10; int n,m,power[maxn],nex[maxn],num[maxn],sq,last[maxn]; inline void init() { sq=sqrt(n*1.0); for(int i=n;i>0;i--) { int ne=i+power[i]; if(ne>n)num[i]=1,nex[i]=ne,last[i]=i; else { if(ne/sq==i/sq)num[i]=num[ne]+1,nex[i]=nex[ne],last[i]=last[ne]; else num[i]=1,nex[i]=ne,last[i]=i; } } } inline void update(int x,int y) { power[x]=y; for(int i=x;i>0&&i/sq==x/sq;i--) { int ne=i+power[i]; if(ne>n)num[i]=1,nex[i]=ne,last[i]=i; else { if(ne/sq==i/sq)num[i]=num[ne]+1,nex[i]=nex[ne],last[i]=last[ne]; else num[i]=1,nex[i]=ne,last[i]=i; } } } inline void query(int x) { int p=x,ans=0,la=last[x]; while(p<=n) { ans+=num[p]; la=last[p]; p=nex[p]; } printf("%d %d\n",la,ans); } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++)scanf("%d",&power[i]); init(); while(m--) { int op,x,y; scanf("%d",&op); if(op)scanf("%d",&x),query(x); else scanf("%d%d",&x,&y),update(x,y); } return 0; }