先分析样例:
| 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| k=1 | 3 | 2 | 1 | 4 | 5 |
| k=2 | 2 | 3 | 1 | 4 | 5 |
| k=3 | 2 | 1 | 3 | 4 | 5 |
| k=4 | 2 | 4 | 3 | 1 | 5 |
进行一轮后,发现结果等价于把 互换了位置,意味着接下来第二轮的时候:
- 会走第一轮 走的路线。
- 会走第一轮 走的路线。
- 会走第一轮 走的路线。
因为他们走的路线相同,所以我们可以把 看成一个整体。(用并查集维护即可)
上菜:
#include<bits/stdc++.h>
inline int read()
{ int x=0;
bool f=0;
char c=getchar();
while(!isdigit(c))f|=(c=='-'),c=getchar();
while(isdigit(c))x=x*10+(c&15),c=getchar();
return f?-x:x;
}
#define read() Read<int>()
namespace pb_ds{
namespace io{
const int MaxBuff=1<<15;
const int Output=1<<23;
char B[MaxBuff],*S=B,*T=B;
#define getc() ((S==T)&&(T=(S=B)+fread(B,1,MaxBuff,stdin),S==T)?0:*S++)
char Out[Output],*iter=Out;
inline void flush(){
fwrite(Out,1,iter-Out,stdout);
iter=Out;
}
}
template<class Type> inline Type Read(){
using namespace io;
register char ch;
register Type ans=0;
register bool neg=0;
while(ch=getc(),(ch<'0' || ch>'9') && ch!='-');
ch=='-'?neg=1:ans=ch-'0';
while(ch=getc(),'0'<= ch && ch<='9') ans=ans*10+ch-'0';
return neg?-ans:ans;
}
template<class Type> inline void Print(register Type x,register char ch='\n'){
using namespace io;
if(!x) *iter++='0';
else{
if(x<0) *iter++='-',x=-x;
static int s[100];
register int t=0;
while(x) s[++t]=x%10,x/=10;
while(t) *iter++='0'+s[t--];
}
*iter++=ch;
}
}
using namespace pb_ds;
using namespace std;
int n,k,num[100005],fa[100005];
vector<int>lg[100005];
set<int>answer[100005];
int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}
int main()
{ n=read(),k=read();
for(register int i=1;i<=n;++i)num[i]=i,fa[i]=i,lg[i].push_back(i);
for(register int i=1;i<=k;++i)
{ int a=read(),b=read();
lg[num[a]].push_back(b);
lg[num[b]].push_back(a);
swap(num[a],num[b]);
}
for(register int i=1;i<=n;++i)
{ int fx=find(i),fy=find(num[i]);
if(fx!=fy)fa[fy]=fx;
}
for(register int i=1;i<=n;++i)
for(register int j=0;j<lg[i].size();++j)
answer[find(i)].insert(lg[i][j]);
for(register int i=1;i<=n;++i)Print(answer[i].size());
io::flush();
return 0;
}