-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcycle_perm.cpp
More file actions
46 lines (44 loc) · 732 Bytes
/
cycle_perm.cpp
File metadata and controls
46 lines (44 loc) · 732 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include<bits/stdc++.h>
using namespace std;
int n,cycle=0,checked[1010];
vector<int> a[1010],adj[1010];
void dfs(int i)
{
if(!checked[i])
{
checked[i]=1;
a[cycle].push_back(adj[i][0]);
dfs(adj[i][0]);
}
else
{
return;
}
}
void display(int i)
{
cout<<a[i][a[i].size()-1]<<" ";
for(int b=0;b<a[i].size();b++)
cout<<a[i][b]<<" ";
cout<<endl;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
int temp;cin>>temp;
adj[i].push_back(temp);
}
for(int i=1;i<=n;i++) // i denotes the position
{
if(!checked[i])
{
++cycle;
dfs(i);
}
}
cout<<cycle<<endl;
for(int i=1;i<=cycle;i++)
display(i);
}