Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define ll long long
- #include <bits/stdc++.h>
- using namespace std;
- const int OO = 1e9;
- const double EPS = 1e-9;
- class PerfectPermutation {
- public:
- vector<vector<int>> graph;
- bool visited[51];
- void dfs(int i) {
- for(int e : graph[i]) {
- if(!visited[e]) {
- visited[e] = 1;
- dfs(e);
- }
- }
- }
- int reorder(vector<int> P) {
- graph.resize(P.size());
- memset(visited,0,sizeof(visited));
- for(int i = 0; i < P.size(); i++) {
- graph[P[i]].push_back(P[P[i]]);
- graph[P[P[i]]].push_back(P[i]);
- }
- int ans = 0;
- for(int i = 0; i < P.size(); i++) {
- if(!visited[i]) {
- visited[i] = 1;
- ans++;
- dfs(i);
- }
- }
- return (ans == 1 ? 0:ans);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement