首页 > 代码库 > HDU--4786 Fibonacci Tree 生成树+贪心?

HDU--4786 Fibonacci Tree 生成树+贪心?

N个顶点,M条边,每条边可能为黑色或是白色( 0 or 1 ),问有没有可能用为斐波那契数的数目的白色边构成一棵生成树。所以需要删掉图中的环,根据每次删掉的边有一个白色边的上限和下限,判断一下中间有没有斐波那契数就可以了。实现方法是根据颜色排序,先放黑色边得到的是最小数目的白色边构成的生成树,先放白色边得到是最大数目的白色边构成的生成树。

#include<cstring>
#include<string>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cctype>
#include<algorithm>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<ctime>
#include<cstdlib>
#include<functional>
#include<cmath>
using namespace std;
#define PI acos(-1.0)
#define MAXN 110000
#define eps 1e-7
#define INF 0x7FFFFFFF
#define seed 131
#define ll long long
#define ull unsigned ll
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

struct node{
    int u,v,col;
}edge[MAXN];
int father[MAXN],fi[90];
int n,m,flag;
bool cmp(node x,node y){
    return x.col>y.col;
}
int find(int x){
    int t = x;
    while(father[t]!=t){
        t = father[t];
    }
    int k = x;
    while(k!=t){
        int temp = father[k];
        father[k] = t;
        k = temp;
    }
    return t;
}
void solve(){
    int i,j=0;
    int flag2 = 0;
    int minm,maxm;
    minm = maxm = 0;
    sort(edge,edge+m,cmp);
    for(i=0;i<m;i++){
        int a = find(edge[i].u);
        int b = find(edge[i].v);
        if(a!=b){
            if(edge[i].col==1)  maxm++;
            father[a] = b;
            j++;
            if(j>=n-1){
                flag2 = 1;
                break;
            }
        }
    }
    if(flag2==0){
        return ;
    }
    for(i=1;i<=n;i++){
        father[i] = i;
    }
    j = 0;
    for(i=m-1;i>=0;i--){
        int a = find(edge[i].u);
        int b = find(edge[i].v);
        if(a!=b){
            if(edge[i].col==1)  minm++;
            father[a] = b;
            j++;
            if(j>=n-1)  break;
        }
    }
    //cout<<minm<<" "<<maxm<<endl;
    for(i=1;i<45;i++){
        if(fi[i]>=minm&&fi[i]<=maxm)
		{
 			 flag = 1;
 			 break;
 		}
    }
}
int main(){
    int i,j,k=1,t;
    int a,b,c;
    fi[1] = 1;
    fi[2] = 2;
    for(i=3;i<45;i++){
        fi[i] = fi[i-1] + fi[i-2];
        //cout<<fi[i]<<" "<<i<<" "<<endl;
    }
    scanf("%d",&t);
    while(t--){
        flag = 0;
        scanf("%d%d",&n,&m);
        for(i=1;i<=n;i++)   father[i] = i;
        for(i=0;i<m;i++){
            scanf("%d%d%d",&a,&b,&c);
            edge[i].u = a;
            edge[i].v = b;
            edge[i].col = c;
        }
        solve();
        if(flag)    printf("Case #%d: Yes\n",k++);
        else    printf("Case #%d: No\n",k++);
    }
    return 0;
}