#include <bits/stdc++.h> using namespace std; const int N = 1e3 + 7; int n, m, res[N]; vector < int > G[N], R[N]; bool vis[N][N]; void read() { scanf("%d%d", &n, &m); for(int i = 0; i < m; i++) { int a, b; char c; scanf("\n%d %d %c", &a, &b, &c); if(c == 'T') { G[a].push_back(b); G[b].push_back(a); R[b].push_back(a); } else { R[a].push_back(b); } } } bool can[N], use[N][N]; vector < int > a[N]; void dfs(int v, int f, int s) { vis[v][f] = 1; a[s].push_back(v); for(auto u: G[v]) if(!vis[u][f] && use[u][f]) dfs(u, f, s); } bool Go(int f) { if(a[f].empty()) return true; for(int i = 1; i <= n; i++) can[i] = 1; for(auto v: a[f]) for(auto u: R[v]) can[u] = 0; for(auto v: a[f]) use[v][f] = 1; int s = 0; for(auto v: a[f]) if(can[v]) s = v; if(s == 0) return false; res[s] = f; use[s][f] = 0; for(auto v: a[f]) { if(use[v][f] && !vis[v][f]) { a[s].clear(); dfs(v, f, s); if(!Go(s)) return false; } } return true; } int main() { read(); for(int i = 1; i <= n; i++) a[0].push_back(i); if(!Go(0)) puts("NIE"); else { int ile = 0; for(int i = 1; i <= n; i++) if(!res[i]) ile++; if(ile > 1) { puts("NIE"); return 0; } for(int i = 1; i <= n; i++) printf("%d\n", res[i]); } return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | #include <bits/stdc++.h> using namespace std; const int N = 1e3 + 7; int n, m, res[N]; vector < int > G[N], R[N]; bool vis[N][N]; void read() { scanf("%d%d", &n, &m); for(int i = 0; i < m; i++) { int a, b; char c; scanf("\n%d %d %c", &a, &b, &c); if(c == 'T') { G[a].push_back(b); G[b].push_back(a); R[b].push_back(a); } else { R[a].push_back(b); } } } bool can[N], use[N][N]; vector < int > a[N]; void dfs(int v, int f, int s) { vis[v][f] = 1; a[s].push_back(v); for(auto u: G[v]) if(!vis[u][f] && use[u][f]) dfs(u, f, s); } bool Go(int f) { if(a[f].empty()) return true; for(int i = 1; i <= n; i++) can[i] = 1; for(auto v: a[f]) for(auto u: R[v]) can[u] = 0; for(auto v: a[f]) use[v][f] = 1; int s = 0; for(auto v: a[f]) if(can[v]) s = v; if(s == 0) return false; res[s] = f; use[s][f] = 0; for(auto v: a[f]) { if(use[v][f] && !vis[v][f]) { a[s].clear(); dfs(v, f, s); if(!Go(s)) return false; } } return true; } int main() { read(); for(int i = 1; i <= n; i++) a[0].push_back(i); if(!Go(0)) puts("NIE"); else { int ile = 0; for(int i = 1; i <= n; i++) if(!res[i]) ile++; if(ile > 1) { puts("NIE"); return 0; } for(int i = 1; i <= n; i++) printf("%d\n", res[i]); } return 0; } |