Is it a tree?
题目链接: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;
}
上一篇: 腾讯云首发Intel Skylake版至强!性能大爆发
下一篇: php微信支付流程是什么