欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Is it a tree?

程序员文章站 2022-03-15 22:57:24
...

题目链接:https://www.nowcoder.com/practice/1c5fd2e69e534cdcaba17083a5c56335?tpId=40&tqId=21365&tPage=2&rp=2&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

题目描述

A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties. There is exactly one node, called the root, to which no directed edges point. Every node except the root has exactly one edge pointing to it. There is a unique sequence of directed edges from the root to each node. For example, consider the illustrations below, in which nodes are represented by circles and edges are represented by lines with arrowheads. The first two of these are trees, but the last is not.
Is it a tree?

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.

Is it a tree?

解析

不能单纯的根据连通+边数等于顶点数-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;
}
相关标签: nowcoder