題目鏈接:https://www.nowcoder.com/practice/1c5fd2e69e534cdcaba17083a5c56335?tpId=40&tqId=21365&tPage=2&rp=2&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking
題目描述
In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.
輸入描述
The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero and less than 10000.
解析
不能單純的根據連通+邊數等於頂點數-1(這個條件等價於除根節點外其他頂點入度均爲1)這兩個條件判斷,還需要加上入度爲0的條件。也可以用並查集來求連通分量的個數。
#include<bits/stdc++.h>
using namespace std;
unordered_set<int> s;
int cnt, vis[10000], inD[10000];
vector<vector<int>> adj;
void dfs(int u) {
vis[u] = 1;
cnt++; //遍歷到的頂點數
int v;
for (int i = 0; i < adj[u].size(); i++) {
v = adj[u][i];
if (vis[v] == 0) dfs(v);
}
}
int main() {
int a, b, i = 1;
while (cin >> a >> b) {
if (a == -1 && b == -1) break;
printf("Case %d is", i++);
if (a == 0 && b == 0) { //空樹
printf(" a tree.\n");
continue;
}
int num = 0, root, inD_0_num=0; //inD_0_num表示入度爲0的結點數
cnt = 0;
memset(vis, 0, sizeof(vis));
memset(inD, 0, sizeof(inD));
s.clear();
adj.clear();
adj.resize(10000);
do { //do...while結構更適合
if (a == 0) break;
num++; //邊數
adj[a].push_back(b);
inD[b]++;
s.insert(a);
s.insert(b); //存頂點數
} while (cin >> a >> b);
for (int k : s) { //判斷入度爲0的頂點數
if (inD[k] == 0) {
inD_0_num++;
if (inD_0_num > 1) break;
root = k;
}
}
if (num == s.size() - 1&&inD_0_num == 1) { //邊數爲頂點數-1,且入度爲0的結點只有一個
dfs(root);
printf("%s", cnt == s.size() ? " " : " not ");
} else printf(" not ");
printf("a tree.\n");
}
return 0;
}