1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| #include<cstdio> #include<vector> #include<queue> #include<map> #define M 100 using namespace std;
vector<int> adjList[M]; bool BFS(int n, int root); int main() { int u, v, ref[M] = {}, Case = 1; map<int, int> Map;
while (scanf("%d%d", &u, &v) && u >= 0) { int i, idx = 0; while (u) { if (!Map.count(u)) Map[u] = ++idx; if (!Map.count(v)) Map[v] = ++idx;
adjList[Map[u]].push_back(Map[v]); ref[Map[v]]++;
scanf("%d%d", &u, &v); }
int root = -1; bool ans = true; for (i = 1; i <= idx; i++) { if (!ref[i]) { if (root != -1) { ans = false; break; }
root = i; } else if (ref[i] > 1) { ans = false; break; } }
if (idx) { if (root == -1) ans = false; else if (ans) ans = BFS(idx, root); }
printf("Case %d is%sa tree.\n", Case++, ans ? " " : " not ");
for (i = 1; i <= idx; i++) { ref[i] = 0; adjList[i].clear(); }
Map.clear(); }
return 0; } bool BFS(int n, int root) { bool isVisit[M] = {}; queue<int> Q; Q.push(root); isVisit[root] = true;
while (!Q.empty()) { int u = Q.front(); Q.pop();
for (int v : adjList[u]) { if (!isVisit[v]) isVisit[v] = true; else return false;
Q.push(v); } }
for (int i = 1; i <= n; i++) if (!isVisit[i]) return false;
return true; }
|