poj2485(MST)

QAQ

点击题目链接

/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :2015
File Name   :
*****************************************/
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
#define MEM(a,b) memset(a,b,sizeof a)
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
struct Edge{
	int u,v,c;
	bool operator < (const Edge& b)const{
		return c < b.c;
	}
}E[500 * 300];
int F[510];
int ans;
int Find(int x){
	if (x == F[x]) return x;
	else return F[x] = Find(F[x]);
}
void init(int n){
	for (int i = 1;i <= n;i++)
		F[i] = i;
}
void Kruskal(int n){
	sort(E,E + ans);
	init(n);
	int cnt = 0;
	int rec;
	for (int i = 0;i < ans;i++){
		int a = E[i].u;
		int b = E[i].v;
		int c = E[i].c;
		if (Find(a) != Find(b)){
			F[Find(a)] = Find(b);
			cnt++;
			rec = c;
		}
		if (cnt == n - 1) break;
	}
	printf("%d\n",rec);
	// if (cnt == n - 1) return ans;
	// else return -1;
}
int g[510][510];
int main()
{	
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	int t,n;
	cin >> t;
	while(t--){
		cin >> n;
		for (int i = 1;i <= n;i++)
			for (int j = 1;j <= n;j++)
				cin >> g[i][j];
		ans = 0;
		for (int i = 1;i <= n;i++){
			for (int j = i + 1;j <= n;j++){
				E[ans].u = i;
				E[ans].v = j;
				E[ans++].c = g[i][j];
			}
		}
		Kruskal(n);
	}
	return 0;
}


你可能感兴趣的:(最小生成树,poj,图论)