Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
简单的并查集实现方法。这个题不可以使用Cin 必须使用scanf,另外在每个scanf后面加上getchar()来清空缓冲区 下面是代码 #include<iostream> #include<stdio.h> #include<string.h> using namespace std; #define MAX_N 100005 int T; int par[MAX_N*2]={0}; int rank[MAX_N*2]; void init(int x){ for(int i=1;i<=x;i++){ par[i]=i; rank[i]=0; } } int find(int x){ if(par[x]==x) return x; else return par[x]=find(par[x]); } void unite(int x,int y){ x = find(x); y = find(y); if(x==y) return; if(rank[x]<rank[y]) par[x]=y; else{ par[y]=x; if(rank[x]==rank[y]) rank[x]++; } } bool same(int x,int y){ return find(x)==find(y); } int main(){ scanf("%d",&T); while(T--){ int M,N; scanf("%d%d",&N,&M); getchar(); memset(par,0,sizeof(par)); init(2*N); for(int i=0;i<M;i++){ char cmd; int c1,c2; //cin>>cmd>>c1>>c2; scanf("%c %d %d",&cmd,&c1,&c2); getchar(); if(cmd=='D'){ unite(c1,c2+N); unite(c1+N,c2); } else{ if(N==2) printf("In different gangs.\n"); else if(same(c1,c2)){ printf("In the same gang.\n"); } else if (same(c1,c2+N)||same(c1+N,c2))printf("In different gangs.\n"); else puts("Not sure yet."); } } } } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator