【并查集】 HDOJ 4786 Fibonacci Tree

就是求出搞成最小生成树的最少白边和最多白边的数量。。。。

#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 100005
#define maxm 200005
#define eps 1e-7
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
//head

struct Edge
{
	int u, v, w;
}e[maxm];
int f[maxn];
int a[maxn];
int n, m, cnt;

int find(int u)
{
	return f[u] = u == f[u] ? f[u] : find(f[u]);
}

bool merge(int a, int b)
{
	int aa = find(a), bb = find(b);
	if(aa != bb) {
		f[aa] = bb;
		return true;
	}
	else return false;
}

void init()
{
	a[0] = 0;
	a[1] = 1;
	for(int i = 2; i <= 100; i++) {
		a[i] = a[i-1] + a[i-2];
		if(a[i] > 100000) {
			cnt = i;
			break;
		}
	}
}

void read()
{
	scanf("%d%d", &n, &m);
	for(int i = 0; i < m; i++) scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w);
}

int cmp(Edge a, Edge b)
{
	return a.w < b.w;
}

void work()
{
	int t1 = 0, t2 = 0, Cnt = 0;
	for(int i = 0; i <= n; i++) f[i] = i;
	for(int i = 0; i < m; i++) Cnt += merge(e[i].u, e[i].v);
	if(Cnt != n-1) {
		printf("No\n");
		return;
	}
	for(int i = 0; i <= n; i++) f[i] = i;
	for(int i = 0; i < m; i++) if(!e[i].w) merge(e[i].u, e[i].v);
	for(int i = 0; i < m; i++) if(e[i].w) t1 += merge(e[i].u, e[i].v) * e[i].w;
	for(int i = 0; i <= n; i++) f[i] = i;
	for(int i = 0; i < m; i++) if(e[i].w) t2 += merge(e[i].u, e[i].v) * e[i].w;
	int ok = lower_bound(a, a+cnt+1, t2) - lower_bound(a, a+cnt+1, t1);
	ok |= binary_search(a+1, a+cnt+1, t1);
	if(ok) printf("Yes\n");
	else printf("No\n");
}

int main()
{
	int _, __;
	init();
	while(scanf("%d", &_)!=EOF) {
		__ = 0;
		while(_--) {
			read();
			printf("Case #%d: ", ++__);
			work();
		}
	}
	
	
	return 0;
}


你可能感兴趣的:(并查集)