Codevs4246 奶牛的身高

来源:互联网 发布:eduline修复完整源码 编辑:程序博客网 时间:2024/09/21 08:53

题目:http://codevs.cn/problem/4246/
分析:带权并查集,注意find中变量不能是全局。
代码:

#include <cstdio>#include <algorithm>#include <cstring>using namespace std;const int Tmax=30005;int n,m,fa[Tmax],height[Tmax];void init(){    memset(height,0,sizeof(height));    int i;    for(i=1;i<=n;i++) fa[i]=i;    return;}int find(int x){    int oldf,newf;    if(fa[x]==x) return x;    oldf=fa[x];    newf=find(fa[x]);    height[x]+=height[oldf];    return fa[x]=newf;}int main(){    int T,i,u,v,w,fx,fy;    bool ok;    scanf("%d",&T);    while(T--)    {        scanf("%d%d",&n,&m);        init();ok=false;        for(i=1;i<=m;i++)        {            scanf("%d%d%d",&u,&v,&w);            if(ok) continue;            if(u==v&&w!=0){                printf("Bessie is blind.\n");                ok=true;                continue;            }            fx=find(u);            fy=find(v);            if(fx==fy){                if(height[u]-height[v]!=w){                    printf("Bessie is blind.\n");                    ok=true;                    continue;                }else continue;            }            else {                fa[fx]=fy;                height[fx]=w+height[v]-height[u];//height[fx]=w+height[v];            }        }        if(!ok) printf("Bessie's eyes are good\n");    }    return 0;}
0 0
原创粉丝点击