POJ-1236.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. using namespace std;
  5. int main() {
  6. ios::sync_with_stdio(false);
  7. cin.tie(nullptr);
  8. int n;
  9. cin >> n;
  10. vector<vector<int>> g(n);
  11. for (int u = 0; u < n; ++u) {
  12. int v;
  13. while (cin >> v && v != 0) g[u].push_back(v - 1);
  14. }
  15. vector<int> dfn(n), low(n), comp(n, -1), st;
  16. vector<bool> in_stack(n);
  17. int timer = 0, count = 0;
  18. auto dfs = [&](auto &&self, int u) -> void {
  19. dfn[u] = low[u] = ++timer; st.push_back(u); in_stack[u] = true;
  20. for (int v : g[u]) {
  21. if (!dfn[v]) self(self, v), low[u] = min(low[u], low[v]);
  22. else if (in_stack[v]) low[u] = min(low[u], dfn[v]);
  23. }
  24. if (dfn[u] == low[u]) {
  25. while (true) {
  26. int v = st.back(); st.pop_back(); in_stack[v] = false; comp[v] = count;
  27. if (v == u) break;
  28. }
  29. ++count;
  30. }
  31. };
  32. for (int v = 0; v < n; ++v) if (!dfn[v]) dfs(dfs, v);
  33. if (count == 1) {
  34. cout << "1\n0\n";
  35. return 0;
  36. }
  37. vector<int> indeg(count), outdeg(count);
  38. for (int u = 0; u < n; ++u) for (int v : g[u]) if (comp[u] != comp[v]) {
  39. ++outdeg[comp[u]]; ++indeg[comp[v]];
  40. }
  41. int sources = 0, sinks = 0;
  42. for (int c = 0; c < count; ++c) {
  43. sources += indeg[c] == 0;
  44. sinks += outdeg[c] == 0;
  45. }
  46. cout << sources << '\n' << max(sources, sinks) << '\n';
  47. }