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]; }
阅读全文
0 0
- hackerrank Journey to the Moon(并查集)
- 并查集 HOJ 2064 Journey to Tibet
- hackerrank Roads and Libraries(DFS/并查集)
- To The Moon 玩后感
- hdu4348 To the moon
- hdu4348 To the moon
- HDU 4348 - To the moon
- hdu 4348 To the moon
- spoj TTM To the moon
- HDU 4348 To the moon
- Thoughts On <To The Moon>
- Under The Moon——6、Spaceship to the Moon
- SPOJ TTM To the moon(主席树+区间操作)
- HDU 4348 To the moon(主席树区间更新)
- HDU 4348 SPOJ TTM To the moon(操作建树)
- SPOJ TO THE MOON 主席树(有动态修改)
- vjudge: spoj--to the moon(主席树区间修改)
- hdu4348:To the moon(可持久化线段树)
- MongoDB--1.安装数据库和可视化工具
- EditText设置字数限制
- 写给所有程序员_回顾学习初期的五个为什么
- Mathematics for computer science-Introduction
- ARM Device Tree
- hackerrank Journey to the Moon(并查集)
- Linux ubuntu16.04 vi编辑器 退出/保存/不保存 /强制退出/覆盖原有文件保存退出
- @Resource、@Autowired、@Qualifier注解详解
- gitbash命令的简单使用--Git Bash简单使用
- HOJ1867 经理的烦恼 树状数组
- HTML5 – 一个访问本地文件的例子
- POJ 3061-Subsequence
- 文件上传获取属性时:File has been moved
- hdu5776sum