HDU 1829 A Bug's Life(带关系的并查集)
2012-08-31 10:18
363 查看
题意:有n个人,给你m对关系,问有没有同性恋的。
思路1:带关系的并查集。
思路2:广搜,这个比较快,刷进第一版
思路1:带关系的并查集。
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> using namespace std; const int M = 1000009; const int N = 2009; int n,m; int fa ; int rt ; int finfa(int k) { if(fa[k]==k) return k; int t = finfa(fa[k]); rt[k] = (rt[k]+rt[fa[k]])%2; return fa[k] = t; } void un(int a,int b) { int a1 = finfa(a),b1 = finfa(b); fa[a1] = b1; rt[a1] = (rt[a]+rt[b]+1)%2; } struct LT{ int to,nex; } L[M<<1]; bool ans ; void init() { scanf("%d%d",&n,&m); ans = false; for(int i=0;i<=n;i++) fa[i] = i,rt[i] = 0; int f,t; for(int i=0;i<m;i++) { scanf("%d%d",&f,&t); if(finfa(f)==finfa(t)&&rt[f]==rt[t]) ans = true; un(f,t); } if(ans) printf("Suspicious bugs found!\n"); else printf("No suspicious bugs found!\n"); printf("\n"); } int main() { freopen("in.txt","r",stdin); int cas,T= 1; scanf("%d",&cas); while(cas--) { printf("Scenario #%d:\n",T++); init(); } return 0; }
思路2:广搜,这个比较快,刷进第一版
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> using namespace std; const int M = 1000009; const int N = 2009; int n,m; struct LT{ int to,nex; } L[M<<1]; int F ,cnt; void add(int a,int b) { L[cnt].to = b; L[cnt].nex = F[a]; F[a] = cnt++; } int sex ; queue<int> que; bool bfs() { while(!que.empty()) que.pop(); memset(sex,-1,sizeof(sex)); for(int i=1;i<=n;i++) if(sex[i]==-1) { sex[i] = 0; que.push(i); while(!que.empty()) { int e = que.front();que.pop(); for(int i=F[e];i;i=L[i].nex) { int to = L[i].to; if((sex[to]!=-1)&&sex[e]==sex[to]) return true; if(sex[to]==-1) { sex[to] = (sex[e]+1)&1; que.push(to); } } } } return false; } int in() { int res=0;char ch=' '; while(ch>'9'||ch<'0')ch=getchar(); res=(ch-'0'); while((ch=getchar())>='0' && ch<='9' ) res=res*10+(ch-'0'); return res; } void init() { //scanf("%d%d",&n,&m); n = in();m = in(); cnt = 1; memset(F,0,sizeof(F)); int f,t; for(int i=0;i<m;i++) f=in(),t=in(),add(f,t),add(t,f); if(bfs()) printf("Suspicious bugs found!\n"); else printf("No suspicious bugs found!\n"); printf("\n"); } int main() { freopen("in.txt","r",stdin); int cas,T= 1; scanf("%d",&cas); while(cas--) { printf("Scenario #%d:\n",T++); init(); } return 0; }
相关文章推荐
- HDU 1829 A Bug's Life(并查集的应用)
- hdu 1829 A Bug's Life(带权并查集)
- hdu 1829 A Bug's Life(种类并查集)
- hdu 1829 A Bug's Life(分组并查集)
- HDU 1829 A Bug's Life (并查集)
- hdu 1829 A Bug's Life ( 并查集 )
- hdu 1829 A Bug's Life(并查集)
- POJ 2492 || HDU 1829:A Bug's Life(并查集)
- HDU 1829 A Bug's Life (分组并查集)
- hdu 1829 &poj 2492 A Bug's Life(判断二分图、带权并查集)
- HDU-1829 A Bug's Life (带权并查集)
- HDU - 1829 A Bug's Life (并查集应用)
- HDU 1829 A Bug's Life (并查集)
- hdu 1829 &poj 2492 A Bug's Life(推断二分图、带权并查集)
- HDU 1829 A Bug's Life(种类并查集)
- hdu 1829 A Bug's Life (基础并查集)
- hdu 1829 A Bug's Life
- HDU 1829 & POJ 2492 A Bug's Life (并查集)
- hdu 1829 A Bug's Life (一个错误的生活)
- hdu 1829:A Bug's Life