zoukankan      html  css  js  c++  java
  • 【CF771A】Bear and Friendship Condition

    题目大意:给定一张无向图,要求如果 A 与 B 之间有边,B 与 C 之间有边,那么 A 与 C 之间也需要有边。问这张图是否满足要求。

    题解:根据以上性质,即:A 与 B 有关系,B 与 C 有关系,那么 A 和 C 也要有关系,因此可以采用并查集加以维护,维护关系的同时顺便维护各个联通块的大小,若符合题目要求,则同一个联通块中的点必须均有关系。因此,最后计算一下每个联通块的应有关系数和最初所给的关系数比较,相等则符合,反之,不符合。

    代码如下

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn=150010;
    
    inline int read(){
        int x=0,f=1;char ch;
        do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
        do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
        return f*x;
    }
    
    int n,m,f[maxn],size[maxn];
    long long tot;
    bool vis[maxn];
    
    int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
    void merge(int x,int y){
        x=find(x),y=find(y);
        if(x==y)return;
        if(size[x]>size[y])swap(x,y);
        f[x]=y,size[y]+=size[x];
    }
    
    void read_and_parse(){
        n=read(),m=read();
        for(int i=1;i<=n;i++)f[i]=i,size[i]=1;
    }
    
    void solve(){
        int T=m;
        while(T--){
            int x=read(),y=read();
            merge(x,y);
        }
        for(int i=1;i<=n;i++)if(!vis[find(i)]){
            vis[find(i)]=1;
            tot+=(long long)size[find(i)]*(size[find(i)]-1)/2;
        }
        puts(tot==m?"YES":"NO");
    }
    
    int main(){
        read_and_parse();
        solve();
        return 0;
    }
    
  • 相关阅读:
    Codeforces 429 A. Xor-tree
    有趣的游戏:Google XSS Game
    三层架构(一个)——什么是三层架构?
    atitit.ajax bp dwr 3.该票据安排使用的流量汇总 VO9o.....
    深入struts2.0(五)--Dispatcher类
    update与fixedupdate差别
    Android 平台 HTTP网速測试 案例 API 分析
    Matlab画图-非常具体,非常全面
    词性标注
    windows消息钩子
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10045897.html
Copyright © 2011-2022 走看看