ツリー互いに素セット

トレーニング4 - Dのタイトル

ツリーは、(NULL、ボイド、何も)のいずれか空であるか、または以下の特性を満たすノード間の有向エッジによって接続された1つまたは複数のノードの集合であり、周知のデータ構造です。

ないエッジ点を向けたルートと呼ばれ、正確に1つのノードが、存在します。

ルートを除くすべてのノードは、それを指して正確に一つのエッジを有します。

各ノードへのルートから有向エッジのユニークな配列があります。

例えば、ノードは円で表され、エッジが矢印付きの線で表されている以下の図を考えます。これらの最初の二つは木ですが、最後ではありません。

彼の問題は、あなたは有向辺によって接続されたノードのコレクションのいくつかの説明が与えられます。これらのそれぞれについて、あなたは、コレクションを満たしている場合、ツリーかどうかの定義を決定することです。

入力

   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. 

出力

   For each test case display the line "Case k is a tree." or the line "Case k is not a tree.", where k corresponds to the test case number (they are sequentially numbered starting with 1). 

サンプル入力

6 8 5 3 5 2 6 4
5 6 0 0

8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0

3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1

サンプル出力

ケース1は、ツリーです。
ケース2は、ツリーです。
ケース3はtree.Sponsorではありません

#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e6 + 5;

int fa[maxn];

void initial(int n)
{
	for (int i = 1; i <= n; i++)
	{
		fa[i] = i;
	}
}

int get(int x)
{
	if (x == fa[x])
		return x;
	return fa[x] = get(fa[x]);
}

void merge(int x, int y)
{
	fa[get(x)] = get(y);
}

int main()
{
	int cas = 0;
	int x, y;
	bool flag = 1;
	set<int> node;
	int edge = 0;
	initial(1e6);
	while (scanf("%d%d", &x, &y) != EOF)
	{
		if (x == -1 && y == -1)
			break;
		if (x == 0 && y == 0)
		{
			if (node.size() != 0 && node.size() != edge + 1)
				flag = 0;
			if (flag)
				printf("Case %d is a tree.\n", ++cas);
			else
				printf("Case %d is not a tree.\n", ++cas);
			initial(1e6);
			flag = 1;
			node.clear();
			edge = 0;
		}
		else
		{
			if (get(x) == get(y))
				flag = 0;
			merge(x, y);
			edge++;
			node.insert(x);
			node.insert(y);
		}
	}
	return 0;
}

アイデア:
判定ツリー条件ではない:①は、空の木であることができる。②環を持っていない。③辺の数(一つだけルートノード)よりも複数のノード。

公開された28元の記事 ウォンの賞賛0 ビュー325

おすすめ

転載: blog.csdn.net/xukeke12138/article/details/104738416
おすすめ