hdu 5441 Travel(离线操作+并查集路径压缩)

来源:互联网 发布:上海培训java 编辑:程序博客网 时间:2024/06/14 05:30

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=5441

解题思路:

题目大意:

给你n个顶点,m条边的一个无向图,q个询问。对于每个询问x,将图中所有小于x的边拿出里啊,组成另外一个图,将一个点a到能

到另一个点b记为有序对<a,b>, 然后让你找出这个图里面有多少个这样的有序对。

算法思想:

当时比赛的时候思维短路了。。。这题肯定是先将所有的询问从小到大排个序,进行离线操作,然后再加边,每次加边时,记录一

下块是否合并,合并,就使两个块的合并在一起,用路径压缩,有序对的数量就加上现在合并后的块的有序对数量,再减去原来那

两个块的有序对数量,如果已经在同一个块中,则不需要任何操作。

AC代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;struct node{    int x,y,l;    bool operator < (const node &a) const{        return l < a.l;    }}no[100005];struct Query{    int id,l;     bool operator < (const Query &a) const{        return l < a.l;    }}qq[5005];int pa[20005];int num[20005];int ans[5005];int findset(int x){    if(x == pa[x])        return pa[x];    return pa[x] = findset(pa[x]);}int main(){    int T;    scanf("%d",&T);    while(T--){        int n,m,q;        scanf("%d%d%d",&n,&m,&q);        for(int i = 0; i <= n; i++){            pa[i] = i;            num[i] = 1;        }        for(int i = 0; i < m; i++)            scanf("%d%d%d",&no[i].x,&no[i].y,&no[i].l);        for(int i = 0; i < q; i++){            scanf("%d",&qq[i].l);            qq[i].id = i;        }        sort(no,no+m);        sort(qq,qq+q);        int x,y,j = 0,sum = 0;        for(int i = 0; i < q; i++){            while(j < m && no[j].l <= qq[i].l){                x = findset(no[j].x);                y = findset(no[j].y);                if(x != y){                    sum += (num[x]+num[y])*(num[x]+num[y]-1)-num[x]*(num[x]-1)-num[y]*(num[y]-1);                    pa[x] = y;                    num[y] += num[x];                }                j++;            }            ans[qq[i].id] = sum;        }        for(int i = 0; i < q; i++)            printf("%d\n",ans[i]);    }    return 0;}


0 0
原创粉丝点击