Alex_tz307

semafor2 - 51p

Dec 3rd, 2020 (edited)
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. ifstream fin("semafor2.in");
  6. ofstream fout("semafor2.out");
  7.  
  8. int N, M, cnt, nr;
  9. vector<vector<pair<int,bool>>> G;
  10. vector<vector<int>> GT, vis;
  11. vector<int> viz, ctc;
  12. stack<int> S;
  13.  
  14. void dfs1(int node) {
  15.     viz[node] = 1;
  16.     for(auto next : G[node])
  17.         if(!viz[next.first])
  18.             dfs1(next.first);
  19.     S.emplace(node);
  20. }
  21.  
  22. void dfs2(int node) {
  23.     viz[node] = 2;
  24.     ctc[node] = cnt;
  25.     for(int next : GT[node])
  26.         if(viz[next] == 1)
  27.             dfs2(next);
  28. }
  29.  
  30. bool dfs(int node, bool colour, int firstN, bool firstC) {
  31.     vis[node][colour] = nr;
  32.     for(auto next : G[node])
  33.         if(ctc[next.first] == ctc[firstN] && next.second != colour && vis[next.first][next.second] != nr) {
  34.             if(next.first == firstN && next.second != firstC)
  35.                 return true;
  36.             if(dfs(next.first, next.second, firstN, firstC))
  37.                 return true;
  38.         }
  39.     return false;
  40. }
  41.  
  42. int main() {
  43.     fin >> N >> M;
  44.     G.resize(N + 1);
  45.     GT.resize(N + 1);
  46.     while(M--) {
  47.         int a, b;
  48.         bool c;
  49.         fin >> a >> b >> c;
  50.         G[a].emplace_back(b, c);
  51.         GT[b].emplace_back(a);
  52.     }
  53.     viz.resize(N + 1);
  54.     for(int i = 1; i <= N; ++i)
  55.         if(!viz[i])
  56.             dfs1(i);
  57.     ctc.resize(N + 1);
  58.     while(!S.empty()) {
  59.         int node = S.top();
  60.         S.pop();
  61.         if(viz[node] == 1) {
  62.             ++cnt;
  63.             dfs2(node);
  64.         }
  65.     }
  66.     vis.resize(N + 1, vector<int>(2));
  67.     for(int i = 1; i <= N; ++i) {
  68.         bool ans = false;
  69.         for(auto vec : G[i])
  70.             if(ctc[vec.first] == ctc[i]) {
  71.                 ++nr;
  72.                 ans |= dfs(vec.first, vec.second, i, vec.second);
  73.                 if(ans)
  74.                     break;
  75.             }
  76.         fout << ans;
  77.     }
  78. }
  79.  
Add Comment
Please, Sign In to add comment