Advertisement
_rashed

SRM441-D1-250 PerfectPermutation

Oct 11th, 2021
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #define ll long long
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. const int OO = 1e9;
  6. const double EPS = 1e-9;
  7.  
  8. class PerfectPermutation {
  9. public:
  10.     vector<vector<int>> graph;
  11.     bool visited[51];
  12.  
  13.     void dfs(int i) {
  14.         for(int e : graph[i]) {
  15.             if(!visited[e]) {
  16.                 visited[e] = 1;
  17.                 dfs(e);
  18.             }
  19.         }
  20.     }
  21.  
  22.     int reorder(vector<int> P) {
  23.         graph.resize(P.size());
  24.         memset(visited,0,sizeof(visited));
  25.         for(int i = 0; i < P.size(); i++) {
  26.             graph[P[i]].push_back(P[P[i]]);
  27.             graph[P[P[i]]].push_back(P[i]);
  28.         }
  29.         int ans = 0;
  30.         for(int i = 0; i < P.size(); i++) {
  31.             if(!visited[i]) {
  32.                 visited[i] = 1;
  33.                 ans++;
  34.                 dfs(i);
  35.             }
  36.         }
  37.         return (ans == 1 ? 0:ans);
  38.     }
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement