china_sjc
unread,Aug 6, 2008, 4:22:37 AM8/6/08Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to 中国矿业大学徐海学院算法课程
源代码:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define M 100001
struct Crime{
int parent,weight;
};
Crime crime[M]; // 所用数据结构
int n,m;
main( ){
int k,one,two;
char order;
// freopen("data.txt","r",stdin);
int kk,X;
scanf("%d",&X);
for(kk=0;kk<X;kk++){
memset(crime,0,sizeof(crime)); //初始化清零
scanf("%d%d",&n,&m);
for(k=0;k<m;k++){
while(1){ // 清除空格等额外字符,有点多虑
order=getchar();
if(order=='D'||order=='A') break;
}
scanf("%d%d",&one,&two);
if(order=='D'){ // 执行命令 D one two
int temp1=one,temp2=two,t1=0,t2=0;
while(crime[temp1].parent!=0) {
t1+=crime[temp1].weight;temp1=crime[temp1].parent;
}// 查找one 所在树的头节点,并计算到头节点的权之和
while(crime[temp2].parent!=0) {
t2+=crime[temp2].weight;temp2=crime[temp2].parent;
} // 查找 two 所在树的头节点,并计算到头节点的权之和
if(temp1!=temp2){
if(t1<t2){ // 若t1<t2 ,把 one 所在树挂到 two上
crime[temp1].parent=temp2;
crime[temp1].weight=(t1-t2+1)%2;
}
else { // 反之,将 two 所在树挂到 one 上。
crime[temp2].parent=temp1;
crime[temp2].weight=(t1-t2+1)%2;
}
}
}
else{ // 执行命令 A one two
int temp1=one,temp2=two,t1=0,t2=0;
while(crime[temp1].parent!=0) {
t1+=crime[temp1].weight;temp1=crime[temp1].parent;
} // 查找one 所在树的头节点,并计算到头节点的权之和
while(crime[temp2].parent!=0) {
t2+=crime[temp2].weight;temp2=crime[temp2].parent;
} // 查找 two 所在树的头节点,并计算到头节点的权之和
if(temp1!=temp2) // 不在同一棵树
printf("Not sure yet.\n");
else if((t2-t1)%2==0) // 权相差为偶数
printf("In the same gang.\n");
else // 权相差为一个奇数
printf("In different gangs.\n");
}
}
}
return 1;
}