Advertisement
tepyotin2

Untitled

Oct 5th, 2023
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <vector>
  4. using namespace std;
  5. int n, m;
  6. const int MAX_N = 3000;
  7. vector<vector<int>> adj(MAX_N);
  8. vector<int> vis(MAX_N);
  9. vector<int> closed(MAX_N);
  10. int nodes = 0;
  11.  
  12. void dfs(int node) {
  13.     if (vis[node] || closed[node]) return;
  14.     // Visit this node if it isn't closed and we haven't visited it yet.
  15.     nodes++;
  16.     vis[node] = true;
  17.    
  18.     for (int u : adj[node]) {
  19.         if (!vis[u]) dfs(u);
  20.     }
  21. }
  22. int main() {
  23.     freopen("closing.in", "r", stdin);
  24.     freopen("closing.out", "w", stdout);
  25.     cin >> n >> m;
  26.     // Read in adjacency list.
  27.     for (int i = 0; i < m; i++) {
  28.         int a, b;
  29.         cin >> a >> b;
  30.         adj[a].push_back(b);
  31.         adj[b].push_back(a);
  32.     }
  33.    
  34.     vector<int> ord(n);
  35.     for (int i = 0; i < n; i++) cin >> ord[i];
  36.     dfs(1);
  37.    
  38.     /*
  39.      * The farm is initially connected if we've visited every node
  40.      * before any of the farms are closed.
  41.      */
  42.     if (nodes == n) {
  43.         cout << "YES\n";
  44.     } else {
  45.         cout << "NO\n";
  46.     }
  47.    
  48.     for (int i = 0; i < n - 1; i++) {
  49.         nodes = 0;
  50.         closed[ord[i]] = true;
  51.         fill(vis.begin(), vis.end(), false);
  52.         // Start DFS from the barn that will close last.
  53.         dfs(ord[n - 1]);
  54.         // Have we visited all the unclosed barns?
  55.         if (nodes == n - i - 1) {
  56.             cout << "YES" << "\n";
  57.         } else {
  58.             cout << "NO" << "\n";
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement