小弟資淺...對於disjiont tree不是很拿手, 能請各位大大幫忙看看哪裡錯嗎
我是用array去裝
填relation ship的方法如下, 如果A是空讓他當root, B當孩子
如果非空, A找到他的root, B直接當root的孩子
判斷關係的方法則是看看, p,q 彼此的root是否相等
請問哪裡有錯, 感謝!
//assign relationship
for(int i=0;i<m;++i){
int a,b;
cin >> a >> b;
if(people[a]==0)
people[b] = a; // p[b] = a;
else if(people[a]>0){
while(people[a]>0){ //read until root
a = people[a];
}
people[b] = a;
}
}
bool friendShipAns(int*people, int p, int q){
//cout << "P:" << p << endl;
//cout << "Q:" << q << endl;
while(people[p]>0){ p = people[p];/*cout << "people[p]:" << people[p] << endl;*/}
while(people[q]>0){ q = people[q];/*cout << "people[q]:" << people[q] << endl;*/}
return (p==q);
}
完整碼
/**********************************************************************************/
/* Problem: a445 "新手訓練系列- 我的朋友很少" from 新手訓練系列 ~ 4*/
/* Language: CPP (1141 Bytes) */
/* Result: NA(score:20) judge by this@ZeroJudge */
/* Author: saitor362320 at 2012-08-23 00:46:09 */
/**********************************************************************************/
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
bool friendShipAns(int*people, int p, int q){
//cout << "P:" << p << endl;
//cout << "Q:" << q << endl;
while(people[p]>0){ p = people[p];/*cout << "people[p]:" << people[p] << endl;*/}
while(people[q]>0){ q = people[q];/*cout << "people[q]:" << people[q] << endl;*/}
return (p==q);
}
int main()
{
int n,m,q;
int* people;
while(cin>>n>>m>>q){
//initial array
people = (int*)(malloc(n*sizeof(int)));
for(int i=0;i<=n;++i) people[i] = 0;
//assign relationship
for(int i=0;i<m;++i){
int a,b;
cin >> a >> b;
if(people[a]==0)
people[b] = a; // p[b] = a;
else if(people[a]>0){
while(people[a]>0){ //read until root
a = people[a];
}
people[b] = a;
}
}
//answer the question
for(int i=0;i<q;++i){
int p1,p2;
cin >> p1 >> p2;
bool ans = friendShipAns(people, p1 , p2);
if(ans)
cout << ":)" << endl;
else
cout << ":(" << endl;
}//exit(1);
//release memory
//free(people);
}
return 0;
}
忘了說: array一開始都是0,
一開始的人當root, 只到最後array為0的index是root
array為正整數(EX:1)的index是該正整數(EX:1)的孩子
[1]0
[2]1
[5]1
2, 5是root的孩子
本題5本來是2的孩子, 我直接讓他成為1的孩子....
本來以為可以節省時間, 第二, 第七個測資還是TLE
好像只過2個測資