Advertisement
999ms

Untitled

May 26th, 2019
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<vector<int> > g;
  5. vector<vector<int> > rg;
  6. vector<int> dependencies;
  7. vector<vector<int> > graph;
  8. int n;
  9. void getDependence(int f, int & ans) {
  10.   ans |= (1<<f);
  11.   for(int v : rg[f]) {
  12.     if((ans & (1<<v)) == 0)
  13.       getDependence(v, ans);
  14.     ans |= (1<<v);
  15.   }
  16. }
  17.  
  18. int checkBit(int val, int bit) {
  19.   return (val>>bit)&1;
  20. }
  21. vector<vector<int> > answer;
  22.  
  23. int getNextBit(int mask, int nxt) {
  24.   int answer = 0;
  25.   nxt -= mask;
  26.   while(nxt) {
  27.     answer++;
  28.     nxt /= 2;
  29.   }
  30.   return answer;
  31. }
  32.  
  33. void buildAnswer(int mask, vector<int> v) {
  34.   if(mask == (1<<n) - 1) {
  35.     answer.push_back(v);
  36.     return;
  37.   }
  38.   for(int nextMask : graph[mask]) {
  39.     vector<int> nextVector = v;
  40.     nextVector.push_back(getNextBit(mask, nextMask));
  41.     buildAnswer(nextMask, nextVector);
  42.   }
  43. }
  44.  
  45. int main() {
  46.   ios_base::sync_with_stdio(false);
  47.   cin.tie(nullptr);
  48.   cin>>n;
  49.   g.resize(n);
  50.   rg.resize(n);
  51.   dependencies.resize(n, 0);
  52.   int m;
  53.   cin>>m;
  54.   for(int i=0; i<m; i++) {
  55.     int f,t;
  56.     cin>>f>>t;
  57.     g[f - 1].push_back(t - 1);
  58.     rg[t - 1].push_back(f - 1);
  59.   }
  60.   for(int i=0; i<n; i++) {
  61.     getDependence(i, dependencies[i]);
  62.   }
  63.  
  64.   set<int> values;
  65.   for(int val : dependencies) {
  66.     if(values.find(val) != values.end()) {
  67.       cout<<"no";
  68.       return 0;
  69.     }
  70.     values.insert(val);
  71.   }
  72.  
  73.  
  74.   graph.resize(1<<n);
  75.  
  76.   for(int mask = 0; mask < (1<<n); mask++) {
  77.     for(int bit = 0; bit < n; bit++) {
  78.       if(!checkBit(mask, bit)) {
  79.         int nextMask = (mask + (1<<bit));
  80.         if((dependencies[bit] & nextMask) == dependencies[bit]) {
  81.           graph[mask].push_back(nextMask);
  82.         }
  83.       }
  84.     }
  85.   }
  86.  
  87.   buildAnswer(0, {});
  88.  
  89.   cout<<answer.size()<<endl;
  90.   for(vector<int> & v : answer) {
  91.     for(int val : v) {
  92.       cout<<val<<" ";
  93.     }
  94.     cout<<"\n";
  95.   }
  96.  
  97.   return 0;
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement