美文网首页
P1700 [USACO19OPEN] Milk Factory

P1700 [USACO19OPEN] Milk Factory

作者: louyang | 来源:发表于2024-10-06 11:17 被阅读0次

由N个点和N-1条边构成的有向图中,求从一个点是否能走到其余所有的点?

#include <iostream>
#include <vector>
using namespace std;

int n, m;
vector<int> adj[101];
bool visited[101];

void dfs(int u) {
  if (visited[u]) {
    return;
  }
  visited[u] = true;

  for (auto v: adj[u]) {
    dfs(v);
  }
}

int main() {
  cin >> n;
  m = n - 1;
  
  for (int i = 1; i <= m; i++) {
    int u, v;
    cin >> u >> v;
    adj[v].push_back(u); // reversed
  }
  
  for (int i = 1; i <= n; i++) {
    dfs(i);
    int cnt = 0;
    for (int j = 1; j <= n; j++) {
      if (visited[j]) {
        cnt++;
        visited[j] = false;
      }
    }
    if (cnt == n) {
      cout << i << endl;
      return 0;
    }
  }
  cout << -1 << endl;
  return 0;
}

相关文章

网友评论

      本文标题:P1700 [USACO19OPEN] Milk Factory

      本文链接:https://www.haomeiwen.com/subject/yfoprjtx.html