朱色虫居
Pages
Home
Featured Posts
2007/03/03
793-Network Connections
/*
"Network Connections"
Level:4.0
Date:2007/3/2
技巧:
利用Union-Find Algorithm & path compresssion
'c': union(node1,node2)
'q': Find_Set(node1) == Find_Set(node2)
*/
#include
#include
using namespace std;
int Find_Set(int); //回傳該node所屬的集合的代表node.
void Link(int,int); //相連兩個集合樹.
void Union(int,int); //聯集(呼叫前兩個function).
const int MAX_N = 30001;
int p[MAX_N], //儲存每個node的parent.
rank[MAX_N]; //儲存每個node的高度.
int main()
{
int num,n,node1,node2,yes,no;
char op;
char input[6];
cin >> num;
while(num--)
{
yes = no = 0;
cin >> n;
for(int i=1; i <= n; i++){ p[i]=i; rank[i]=0; } cin.ignore(); while(gets(input) != NULL && sscanf(input,"%c %d %d",&op,&node1,&node2)==3) { if(op == 'c') Union(node1,node2); else if(op == 'q'){ if(Find_Set(node1) == Find_Set(node2)) yes++; else no++; } } cout << yes << "," << no << endl; if(num) cout << endl; } // while(1); } int Find_Set(int x) { //若x不是root, 便將parent指向root, 並回傳root node. if(x != p[x]) p[x] = Find_Set(p[x]); //recursive find root. return p[x]; } void Link(int x, int y) { if( x == y) //x,y屬同一個Set, 不需相連. return; //小樹串到大樹下. if(rank[x] > rank[y]){
p[y] = x;
}
else{
p[x] = y;
if(rank[x] == rank[y]) //兩棵樹一樣高時, 合成樹的高度會長高一個單位.
rank[y]++;
}
}
void Union(int x, int y)
{
Link(Find_Set(x),Find_Set(y)); //找到兩個node分屬的Set, 並將兩個set相連.
}
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment