hackerrank Journey to the Moon(并查集)

来源:互联网 发布:帝国cms商业版破解版 编辑:程序博客网 时间:2024/05/16 08:14

题目:https://www.hackerrank.com/challenges/journey-to-the-moon/problem
题意:给你p对人,每一对都是生活在同一个城市中的,让你选不在同一城市的两个人,求方案数
思路:肯定是用并查集的,统计每个个数,很容易想到容斥,即C(n,2)-sum(C(cnt,2))
然而开始用的map统计wa(好像因为有序号为0的顶点,不管了),然后改了并查集统计就A了

1.容斥代码:

#include <bits/stdc++.h>using namespace std;const int N = 100005;int f[N];int mp[N];int getf(int x){    return x == f[x] ? x : f[x] = getf(f[x]);}void merge(int x,int y){    int fx = getf(x);    int fy = getf(y);    if(fx != fy){        f[fy] = fx;        mp[fx] += mp[fy];        mp[fy] = 0;    }}int main(){    int n,p,u,v;;    scanf("%d%d",&n,&p);    for(int i = 0;i < n;i++)        f[i] = i,mp[i] =1;    while(p--)    {        scanf("%d%d",&u,&v);        merge(u,v);    }    long long sum = n*(n-1ll)/2;    for(int i = 0;i < n;i++)        if(mp[i])            sum -= mp[i]*(mp[i]-1ll)/2;    printf("%lld\n",sum);    return 0;}

2.迭代统计代码:

    long long sum = 0,cnt = 0;    for(int i = 0;i < n;i++){        sum += cnt*mp[i];        cnt += mp[i];    }
原创粉丝点击