Hdu 1829 A Bug's Life && Poj 1182 食物链 (并查集偏移量的应用)
2012-05-01 13:51
435 查看
复习了一下并查集偏移量的应用,A Bug's Life比食物链简单些,偏移量只有0和1。
偏移量:维护所有集合的根的偏移量都为0。在集合合并时,若两集合对应偏移量不同,改变被合并集合根的偏移量,而集合内部的偏移量暂不改变,在以后查询某点偏移量时,先调用find函数,在find函数中递归更新偏移量值。
Hdu 1829 A Bug's Life
输入可交配的虫子,判断有没有同性交配
Poj 1182 食物链
偏移量:维护所有集合的根的偏移量都为0。在集合合并时,若两集合对应偏移量不同,改变被合并集合根的偏移量,而集合内部的偏移量暂不改变,在以后查询某点偏移量时,先调用find函数,在find函数中递归更新偏移量值。
Hdu 1829 A Bug's Life
输入可交配的虫子,判断有没有同性交配
#include<iostream> #include<algorithm> #include<cmath> #include<cstdio> #include<cstring> using namespace std; int p[2005], g[2005], n, flag, root[2005]; void init(){ memset(g, 0, sizeof(g)); for(int i=0; i<=n; i++){ p[i]=i; root[i]=0; } flag=0; } int find(int x){ if(p[x]==x) return x; int t=find(p[x]); g[x]=(g[x]+g[p[x]])%2; p[x]=t; return p[x]; } void union_set(int x, int y){ int x1=find(x), y1=find(y); if(root[x1]<root[y1]){ p[x1]=y1; if(g[x]==g[y])g[x1]=1; } else { p[y1]=x1; if(g[x]==g[y])g[y1]=1; } if(root[x1]==root[y1])root[x1]++; } int main(){ //freopen("1.txt", "r", stdin); int T, i, x, y, m, cas=1, x1, y1; scanf("%d", &T); while(T--){ scanf("%d%d", &n, &m); init(); while(m--){ scanf("%d%d", &x, &y); if(flag)continue; x1=find(x);y1=find(y); if(x1==y1){ if(g[x]==g[y]) flag=1; } else { union_set(x, y); } } if(flag) printf("Scenario #%d:\nSuspicious bugs found!\n\n", cas++); else printf("Scenario #%d:\nNo suspicious bugs found!\n\n", cas++); } return 0; }
Poj 1182 食物链
#include<iostream> #include<algorithm> #include<cmath> #include<cstdio> #include<cstring> #include<stack> #include<queue> using namespace std; int p[50005], g[50005], n, k, ans; void init(){ memset(g, 0, sizeof(g)); for(int i=0; i<=n; i++){ p[i]=i; } ans=0; } int find(int x){ if(p[x]==x) return x; int t=find(p[x]); g[x]=(g[x]+g[p[x]])%3; p[x]=t; return p[x]; } void check(int d,int x,int y){ int t1=find(x),t2=find(y); if(t1==t2){ if(d==1){ if(g[x]!=g[y]) ans++; } else if((g[y]-g[x]+3)%3!=d) ans++; return; } p[t1]=t2; if(d==1) g[t1]=(g[y]-g[x]+6)%3; else g[t1]=(g[y]-g[x]+1+6)%3; } int main(){ //freopen("1.txt", "r", stdin); int i, x, y, d; scanf("%d%d", &n, &k); init(); while(k--){ scanf("%d%d%d", &d, &x, &y); if(x>n||y>n||(d==2&&x==y)){ ans++;continue; } check(d, x, y); } printf("%d\n", ans); return 0; }
相关文章推荐
- hdu 1829 &poj 2492 A Bug's Life(推断二分图、带权并查集)
- POJ 2492 || 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 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 & POJ 2492 A Bug's Life (并查集)
- HDU 1829 A Bug's Life (并查集)
- POJ 2492 A Bug's Life(种类并查集 + 偏移量)
- hdu 1829 A Bug's Life(带权并查集)
- poj 1703 , hdu 1729 , poj 1182 并查集偏移量应用
- hdu 1829 A Bug's Life ( 并查集 )
- Hdu 1892&&Poj 2492 A Bug's Life[判断二分图 || 种类并查集]
- HDU 1829 && POJ 2492 A Bug's Life(种类并查集)
- HDU 1829 A Bug's Life(种类并查集)