


5 2 5 4 3 1 3 1 2 3
(1 2 5)(3 4) (1)(2)(3)
找循环节,用while循环就可以了,注意输出格式。
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxn=100010;
int num[maxn];
bool vis[maxn];
int n;
void getCircle()
{
memset(vis,0,sizeof(vis));
int t;
bool ok=0;
for(int i=1;i<=n;i++)
{
int temp=i;
if(!vis[temp])
printf("(");
while(!vis[temp])
{
t=temp;
vis[temp]=true;
temp=num[temp];
if(!vis[temp])
printf("%d ",t);
else
{
printf("%d",t);
ok=1;
}
}
if(ok)
{
printf(")");
ok=0;
}
}
printf("\n");
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);
getCircle();
}
return 0;
}
[BestCoder Round #7] hdu 4985 Little Pony and Permutation (找循环节)
原文地址:http://blog.csdn.net/sr_19930829/article/details/38975797