Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- vector<set<int> > rg;
- vector<int> dependencies;
- vector<vector<int> > graph;
- int n;
- void getDependence(int f, int & ans) {
- ans |= (1<<f);
- for(int v : rg[f]) {
- if((ans & (1<<v)) == 0)
- getDependence(v, ans);
- ans |= (1<<v);
- }
- }
- int checkBit(int val, int bit) {
- return (val>>bit)&1;
- }
- vector<vector<int> > answer;
- int getNextBit(int mask, int nxt) {
- int answer = 0;
- nxt -= mask;
- while(nxt) {
- answer++;
- nxt /= 2;
- }
- return answer;
- }
- void buildAnswer(int mask, vector<int> v) {
- if(mask == (1<<n) - 1) {
- answer.push_back(v);
- return;
- }
- for(int nextMask : graph[mask]) {
- vector<int> nextVector = v;
- nextVector.push_back(getNextBit(mask, nextMask));
- buildAnswer(nextMask, nextVector);
- }
- }
- struct Answer {
- vector<int> v;
- Answer(vector<int> v) {
- this->v = v;
- }
- bool operator < (const Answer & o) {
- for(int i = 0; i < (int)o.v.size();i++) {
- if(v[i] != o.v[i]) {
- return v[i] < o.v[i];
- }
- }
- }
- };
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cin>>n;
- rg.resize(n);
- dependencies.resize(n, 0);
- int m;
- cin>>m;
- for(int i=0; i<m; i++) {
- int f,t;
- cin>>f>>t;
- if(f == t) {
- cout << "no";
- return 0;
- }
- rg[t - 1].insert(f - 1);
- }
- for(int i=0; i<n; i++) {
- getDependence(i, dependencies[i]);
- }
- set<int> values;
- for(int val : dependencies) {
- if(values.find(val) != values.end()) {
- cout<<"no";
- return 0;
- }
- values.insert(val);
- }
- graph.resize(1<<n);
- for(int mask = 0; mask < (1<<n); mask++) {
- for(int bit = 0; bit < n; bit++) {
- if(!checkBit(mask, bit)) {
- int nextMask = (mask + (1<<bit));
- if((dependencies[bit] & nextMask) == dependencies[bit]) {
- graph[mask].push_back(nextMask);
- }
- }
- }
- }
- buildAnswer(0, {});
- cout<<answer.size()<<endl;
- vector<Answer> vect;
- for(vector<int> & v : answer) {
- vect.push_back(v);
- }
- sort(vect.begin(), vect.end());
- for(auto a : vect) {
- for(int val : a.v) {
- cout << val << " ";
- }
- cout << "\n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement