长春网络赛 travel hdu5441

并查集绝对的水题,可是读错题意了,2333

好坑队友

将边排序,将访问的q按从小到大排序

for遍历q

如果这个边小于或者是等于限度的加入并查集

建一个cnt数组计算每个连通块的点个数

初始化为1

具体看代码

/********************************************
Author         :Crystal
Created Time   :
File Name      :
********************************************/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <climits>
#include <string>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <sstream>
#include <cctype>
using namespace std;
typedef long long ll;
typedef pair<int ,int> pii;
#define MEM(a,b) memset(a,b,sizeof a)
#define CLR(a) memset(a,0,sizeof a);
const int inf = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
#define LOCAL
struct Edge{
    int u;
    int v;
    int c;
}edge[100001];
int qq[5001];
ll sum;
map<int,int> mp;
int par[100001];
ll cnt[100001];
int cpy[100001];
bool cmp(Edge a,Edge b){
    return a.c < b.c;
}
int find(int u){
    if(par[u]!=u){
        par[u]=find(par[u]);
    }
    return par[u];
}
void Union(int x,int y){
    x = find(x);
    y = find(y);
    if(x==y){
        return;
    }
    else{
        sum += cnt[x]*cnt[y];
        cnt[y]+=cnt[x];
        par[x]=y;
    }
}
int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
//    freopen("out.txt","w",stdout);
#endif
    int t;cin >> t;
    while(t--){
        mp.clear();
        int n,m,q;
        scanf("%d%d%d",&n,&m,&q);
        for(int i=1;i<=m;i++){
            scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].c);
        }
        for(int i=1;i<=q;i++){
            scanf("%d",&qq[i]);
            cpy[i]=qq[i];
        }
        sort(qq+1,qq+q+1);
        sort(edge+1,edge+1+m,cmp);
        int j=1;
        int now;
        sum = 0;
        for(int i=0;i<=n;i++)par[i]=i;
        for(int i=1;i<=n;i++)cnt[i]=1;
        for(int i=1;i<=q;i++){
            while(edge[j].c <= qq[i] && j <= m){
                Union(edge[j].u,edge[j].v);
                j++;
            }
            mp[qq[i]]=sum;
        }
        for(int i=1;i<=q;i++){
            cout << mp[cpy[i]]*2 << endl;
        }
    }
    return 0;
}


你可能感兴趣的:(并查集)