권력 을 가지 고 함께 조사 하여 모으다.

예제 링크:
http://acm.hdu.edu.cn/showproblem.php?pid=3038
제목:
 
분석: 
 
AC 코드:
#include
#define ll long long
#define pii pair
using namespace std;
const int maxn=2e5+7;
const int mod=1e9+7;
ll offe[maxn],boss[maxn];
int fin(int x){
    if(x==boss[x])return x;
    int z=boss[x];
    int y=fin(boss[x]);
    offe[x]+=offe[z];
    boss[x]=y;
    return y;
}
int main()
{
    int n,m,ans=0;
    while(scanf("%d %d",&n,&m)==2){
        ans=0;
        for(int i=0;i<=n;i++)boss[i]=i,offe[i]=0;
        for(int i=1;i<=m;i++){
            int l,r,x;
            scanf("%d %d %d",&l,&r,&x);
            l--;
            if(fin(l)==fin(r)){
                if(offe[l]-offe[r]!=x)ans++;
            }else{
                int fl=fin(l),fr=fin(r);
                boss[fl]=fr;
                offe[fl]=x-offe[l]+offe[r];
            }
        }
        printf("%d
",ans); } return 0; }

 
 
예제 2 링크:
https://codeforces.com/problemset/problem/1290/C
제목:
 
 
분석: 
 
 
 
 
 참고:https://www.cnblogs.com/uid001/p/12272628.html
AC 코드:
#include
#define ll long long
using namespace std;
const int maxn=3e5+7;
vectorve[maxn];
int boss[maxn*2],sz[maxn*2],n,k;
char S[maxn];
int fin(int x){
    if(x==boss[x])return x;
    return boss[x]=fin(boss[x]);
}
void unio(int x,int y){
    x=fin(x),y=fin(y);
    if(x!=y){
        boss[x]=y;
        sz[y]+=sz[x];
    }
}
int cal(int x){
    return min(sz[fin(x)],sz[fin(x+k)]);
}
int main(){
    scanf("%d %d",&n,&k);
    scanf("%s",S+1);
    for(int i=1;i<=2*k+1;i++)boss[i]=i;
    for(int i=k+1;i<=2*k;i++)sz[i]=1;
    sz[2*k+1]=1e9;
    for(int i=1;i<=k;i++){
        int num,x;
        scanf("%d",&num);
        while(num--){
            scanf("%d",&x);
            ve[x].push_back(i);
        }
    }
    int ans=0;
    for(int i=1;i<=n;i++){
         if(ve[i].size()==1){
              ans-=cal(ve[i][0]);
              if(S[i]=='1')unio(ve[i][0]+k,2*k+1);
              else unio(ve[i][0],2*k+1);
              ans+=cal(ve[i][0]);
         }else if(ve[i].size()==2){
            int a=ve[i][0],b=ve[i][1];
            if(fin(a)!=fin(b)&&fin(a)!=fin(b+k)){
                ans-=(cal(a)+cal(b));
                if(S[i]=='1')unio(a,b),unio(a+k,b+k);
                else unio(a,b+k),unio(a+k,b);
                ans+=cal(a);
            }
         }
         printf("%d
",ans); } return 0; }

좋은 웹페이지 즐겨찾기