jlu 2776 Problem G 並查集

http://acm.jlu.edu.cn/joj/showproblem.php?pid=2776

每一次都要記錄每一個集合中元素的數量後再處理,否則用兩重循環現場處理會超時。並且每一次計算時有個強制類型轉換問題,就因爲沒有轉換而提交錯誤了好幾次,很是悲劇啊。

#include <stdio.h>
#include <string.h>

#define MAX 200005

int father[MAX];
int numb[MAX];

int n;

typedef struct _node
{
	int from;
	int to;
}node;

node no[MAX];

void init()
{
	int i;
	for(i = 1; i <= n; i ++){
		father[i] = i;
		numb[i] = 1;
	}
}

int getfather(int x)
{
	int r=x;
	while(father[x] != x)
		x = father[x];
	int a;
	while(r != x)
	{
		a = father[r];
		father[r] = x;
		r = a;
	}
	return x;
}

int get(int x)
{
	while(x != father[x])
		x = father[x];
	return x;
}

int main()
{
//	freopen("input.txt", "r", stdin);
	int i, j, nu;
	long long tot, tmp, res;
	int a, b, c, fa, fb, tfa, tfb;
	while(scanf("%d", &n)!=EOF){
		if(n == 1){
			printf("0\n");
			continue;
		}
		init();
		tot = (long long)n*(n-1)/2;
		nu = 0;
		for(i = 0; i < n - 1; i ++){
			scanf("%d%d%d", &a, &b, &c);
			if(c == 1){
				no[nu].from = a;
				no[nu ++].to = b;
			}
			if(c == 0){
				fa = getfather(a);
				fb = getfather(b);
				father[fb] = fa;
				numb[fa] = numb[fa] + numb[fb];
			}
		}
		tmp = -1;
		for(i = 0; i < nu; i ++){
			fa = get(no[i].from);
			fb = get(no[i].to);
			int tp = numb[fa] + numb[fb];
			res = (long long)tp*(tp-1)/2;
			if(tmp <= res){
				tmp = res;
				tfa = fa;
				tfb = fb;
			}
			
		}//for
		if(tmp != -1){
			for(j = n; j >= 1; j --){
				if(father[j] == j && j != tfa && j != tfb){
				//	printf("num = %d\n", num);
					tmp += (long long)numb[j]*(numb[j]-1)/2;
				}
			}
			printf("%lld\n", tot - tmp);
		}
		else printf("0\n");
	}
	return 0;
}


發佈了79 篇原創文章 · 獲贊 20 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章