Advertisement
DuongNhi99

QBCIRARC - VOI06

Jan 12th, 2022
782
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5. using pii = pair<int, int>;
  6.  
  7. const int maxN = 1e3 + 5;
  8. const int INF = 1e9 + 7;
  9.  
  10. int n, m;
  11. vector<int> graph[maxN];
  12.  
  13. int cycle = 0;
  14. bool act[maxN], visited[maxN];
  15. bool connect[maxN][maxN], skip[maxN][maxN];
  16.  
  17. void dfs(int u) {
  18.     act[u] = visited[u] = 1;
  19.     for (int v : graph[u]) {
  20.         if (!connect[u][v]) continue;
  21.  
  22.         if (act[v]) { // cycle found
  23.           ++cycle;
  24.           return;
  25.         }
  26.         else if (!visited[v]) dfs(v);
  27.     }
  28.     act[u] = 0;
  29. }
  30.  
  31. bool check() {
  32.     cycle = 0;
  33.     memset(visited, 0, sizeof(visited));
  34.     memset(act, 0, sizeof(act));
  35.     for (int i = 1; i <= n && cycle == 0; i++)
  36.         if (!visited[i]) dfs(i);
  37.     return (cycle > 0);
  38. }
  39.  
  40. int main() {
  41. #ifdef LOCAL
  42.     freopen("in1.txt", "r", stdin);
  43. #else
  44.     freopen("QBCIRARC - VOI06.inp", "r", stdin);
  45.     freopen("QBCIRARC - VOI06.out", "w", stdout);
  46. #endif
  47.     ios_base::sync_with_stdio(false);
  48.     cin.tie(nullptr);
  49.  
  50.     cin >> n >> m;
  51.     for (int i = 1; i <= m; ++i) {
  52.         int u, v; cin >> u >> v;
  53.         if (connect[u][v]) {
  54.             skip[u][v] = 1;
  55.             continue;
  56.         }
  57.         graph[u].push_back(v);
  58.         connect[u][v] = 1;
  59.     }
  60.  
  61.     if (!check()) {
  62.         cout << -1 << '\n';
  63.         return 0;
  64.     }
  65.  
  66.     vector<pii> edge;
  67.     for (int u = 1; u <= n; ++u) {
  68.         for (int v: graph[u]) {
  69.             if (skip[u][v]) continue;
  70.             connect[u][v] = 0;
  71.             if (!check()) edge.push_back({u, v});
  72.             connect[u][v] = 1;
  73.         }
  74.     }
  75.  
  76.     cout << (edge.size() == 0 ? -1: edge.size()) << '\n';
  77.     sort(edge.begin(), edge.end());
  78.     for (auto it : edge)
  79.         cout << it.first << ' ' << it.second << '\n';
  80.  
  81.     return 0;
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement