Skip to content

Instantly share code, notes, and snippets.

@henrybear327
Created October 14, 2017 08:09
Show Gist options
  • Save henrybear327/71420f0b3c8f50c7709f2514cc89af0c to your computer and use it in GitHub Desktop.
Save henrybear327/71420f0b3c8f50c7709f2514cc89af0c to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
#define N 10010
typedef pair<int, int> ii;
void solve(int n)
{
int inp[n + 1];
for(int i = 1; i <= n; i++)
scanf("%d", &inp[i]);
// for(int i = 1; i <= n; i++)
//printf("%d%c", inp[i], i == n ? '\n' : ' ');
vector<int> g[N];
int in[N] = {0};
int out[N] = {0};
for(int i = 1; i <= n; i++) {
g[i].push_back(inp[i]);
in[inp[i]]++;
out[i]++;
}
vector<int> s;
for(int i = 1; i <= n; i++) {
if(in[i] == 0)
s.push_back(i);
}
vector<ii> ans;
for(int i = 0; i < (int) s.size(); i++) {
int cnt = 0;
int who = s[i];
// printf("cnt %d who %d\n", cnt, who);
while((int)g[who].size() > 0) {
// printf("cnt %d who %d\n", cnt, who);
cnt++;
who = g[who][0];
}
ans.push_back(ii(s[i], cnt));
}
sort(ans.begin(), ans.end());
printf("%d", (int)ans.size());
for(int i = 0; i < (int)ans.size(); i++)
printf(" %d %d", ans[i].first, ans[i].second);
printf("\n");
}
int main()
{
int n;
while(scanf("%d", &n) == 1 && n)
solve(n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment