5-8 哈利·波特的考试 (25分)

#include <iostream>
#include <vector>
#include <string.h>

using namespace std;

struct node
{
	int next, dis;
};

int tree[110], sum[110], flag[110];

int findroot(int root)
{
	if(tree[root] == -1)
	{
		return root;
	}
	else
	{
		tree[root] = findroot(tree[root]);
		return tree[root];
	}
}

int getrootcount(int n)
{
	int i, count = 0;
	for(i = 1; i <= n; i++)
	{
		if(tree[i] == -1)
		{
			count++;
		}
	}

	return count;
}

void init(int index)
{
	flag[index] = 1;
	sum[index] = 1;
	tree[index] = -1;
}

void buildrelation(int index[2])
{
	int i;
	for(i = 0; i < 2; i++)
	{
		if(flag[index[i]] == 0)
		{
			init(index[i]);
		}
		else
		{
			index[i] = findroot(index[i]);
		}
	}

	if(index[0] == index[1])
	{
		return;
	}

	int index0 = index[0], index1 = index[1];
	if(sum[index1] > sum[index0])
	{
		index0 = index[1];
		index1 = index[0];
	}

	tree[index1] = index0;
	sum[index0] += sum[index1];
}

int main()
{
	int n, m;
	scanf("%d%d", &n, &m);

	int i, a, b, index[2];
	vector<node> v[110];
	node nod;

	for(i = 1; i <= m; i++)
	{
		scanf("%d%d%d", &index[0], &index[1], &nod.dis);

		nod.next = index[1];
		v[index[0]].push_back(nod);

		nod.next = index[0];
		v[index[1]].push_back(nod);

		buildrelation(index);
	}

	if(getrootcount(n) > 1)
	{
		printf("0\n");
		return 0;
	}

	int mark[110][110], dis[110][110], maxdis[110];
	memset(mark, 0, sizeof(mark));
	memset(dis, -1, sizeof(dis));

	int p, j, size, k, next, nextdis, curdis, min;
	for(i = 1; i <= n; i++)
	{
		p = i;
		mark[i][p] = 1;
		dis[i][p] = 0;

		for(j = 1; j < n; j++)
		{
			size = v[p].size();
			for(k = 0; k < size; k++)
			{
				next = v[p][k].next;
				if(mark[i][next] == 1) 
				{
					continue;
				}

				nextdis = dis[i][p] + v[p][k].dis;
				curdis = dis[i][next];

				if(curdis == -1 ||curdis > nextdis)
				{
					dis[i][next] = nextdis;
				}
			}

			min = 100000000;
			for(k = 1; k <= n; k++)
			{
				if(mark[i][k] == 1 || dis[i][k] == -1)
				{
					continue;
				}

				if(dis[i][k] < min)
				{
					min = dis[i][k];
					p = k;
				}
			}

			mark[i][p] = 1;
		}

		maxdis[i] = dis[i][p];
	}

	min = maxdis[1];
	int minindex = 1;

	for(i = 2; i <= n; i++)
	{
		if(maxdis[i] < min)
		{
			min = maxdis[i];
			minindex = i;
		}
	}

	printf("%d %d\n", minindex, min);

	system("pause");
	return 0;
}

 

posted on 2025-11-29 14:58  王景迁  阅读(0)  评论(0)    收藏  举报

导航