1. 程式人生 > 實用技巧 >L2-010 排座位-easy-並查集

L2-010 排座位-easy-並查集

#include<iostream>
#define MAXSIZE 101
using namespace std;
int pre[MAXSIZE];
int army[MAXSIZE][MAXSIZE];
int find (int x) {
	int root = x;
	while(pre[root] != root) {
		root = pre[root];
	}
	return root;
}
void join (int a, int b) {
	int r_a = find(a), r_b = find(b);
	if (r_a != r_b) {
		pre[r_a] = r_b;
	}
	return;
}
int main() {	
    int N, M, K;
    scanf("%d %d %d", &N, &M, &K);
    for (int i = 0; i <= N; ++i) 
    	pre[i] = i;
    /*for (int i = 0; i <= N; ++i)
    	for (int j = 0; j <= N; ++j)
			army[i][j] = 1;	*/
    int a, b, lation;
    for (int i = 0; i < M; ++i) {
    	scanf ("%d %d %d", &a, &b, &lation);
    	army[a][b] = army[b][a] = lation;
    	if (lation == 1)
			join(a, b);
	}
	for (int i = 0; i < K; ++i) {
		scanf("%d %d", &a, &b);
		if ( find (a) == find (b) ){
			if (army[a][b] == -1)
				cout << "OK but...\n";
			else 
				cout << "No problem\n"; 
		}
		else if (army[a][b] != -1)
			cout << "OK\n";		
		else
			cout << "No way\n";
	}
    return 0;
}