zoukankan      html  css  js  c++  java
  • 数石子RQNOJ 并查集

    巧妙的并查集。对于 i,j,k  可以表示  d[j] - d[i-1]= k;若i,j有公共祖先 则可以求出 分别到 祖先的距离,差值就是答案。

    #include<stdio.h>
    #include<iostream>
    #include<string.h>
    #include<queue>
    #include<stack>
    #include<list>
    #include<stdlib.h>
    #include<algorithm>
    #include<vector>
    #include<map>
    #include<set>
    #include <fstream>
    using namespace std;
    
    const int Maxn=5555;
    
    int father[Maxn];
    int dist[Maxn];
    int getfather(int x)
    {
        //cout<<x<<endl;system("pause");
        if(x==father[x]) return x;
        int t=getfather(father[x]);
        dist[x]+=dist[father[x]];
        return father[x]=t;
    }
    
    int main()
    {
        int n,m,k;
        int a,b,c;
        scanf("%d%d%d",&n,&m,&k);
        for(int i=0;i<=n;i++)
            father[i]=i;
        memset(dist,0,sizeof(dist));
        for(int i=0;i<m;i++){
            scanf("%d%d%d",&a,&b,&c);
            int fa=getfather(a-1);int fb=getfather(b);
            if(fa==fb) continue;
            father[fa]=fb;
            dist[fa]=c+dist[b]-dist[a-1];
        }
        for(int i=0;i<k;i++){
            scanf("%d%d",&a,&b);
            int fa=getfather(a-1);int fb=getfather(b);
            if(fa!=fb) {
                printf("UNKNOWN
    ");
            }
            else{
                printf("%d
    ",dist[a-1]-dist[b]);
            }
        }
        return 0;
    }
    

      

  • 相关阅读:
    MinGW GCC 7.1.0 2017年6月份出炉啦
    java面试题-框架篇九
    spring-AOP原理
    spring的bean管理(注解)
    23种设计模式(1)-单例模式
    SSH框架面试题集锦
    JQuery基础
    实现用户注册
    spring与hibernate的整合
    spring-IOC理解1
  • 原文地址:https://www.cnblogs.com/yigexigua/p/3845181.html
Copyright © 2011-2022 走看看