1. 程式人生 > >PTAL2-010 排座位解題報告---並查集的運用

PTAL2-010 排座位解題報告---並查集的運用

                                       L2-010 排座位 (25 分)

佈置宴席最微妙的事情,就是給前來參宴的各位賓客安排座位。無論如何,總不能把兩個死對頭排到同一張宴會桌旁!這個艱鉅任務現在就交給你,對任何一對客人,請編寫程式告訴主人他們是否能被安排同席。

輸入格式:

輸入第一行給出3個正整數:N(≤100),即前來參宴的賓客總人數,則這些人從1到N

編號;M為已知兩兩賓客之間的關係數;K為查詢的條數。隨後M行,每行給出一對賓客之間的關係,格式為:賓客1 賓客2 關係,其中關係為1表示是朋友,-1表示是死對頭。注意兩個人不可能既是朋友又是敵人。最後K行,每行給出一對需要查詢的賓客編號。

這裡假設朋友的朋友也是朋友。但敵人的敵人並不一定就是朋友,朋友的敵人也不一定是敵人。只有單純直接的敵對關係才是絕對不能同席的。

輸出格式:

對每個查詢輸出一行結果:如果兩位賓客之間是朋友,且沒有敵對關係,則輸出No problem;如果他們之間並不是朋友,但也不敵對,則輸出OK;如果他們之間有敵對,然而也有共同的朋友,則輸出OK but...;如果他們之間只有敵對關係,則輸出No way

輸入樣例:

7 8 4
5 6 1
2 7 -1
1 3 1
3 4 1
6 7 -1
1 2 1
1 4 1
2 3 -1
3 4
5 7
2 3
7 2

輸出樣例:

No problem
OK
OK but...
No way

並查集連通所有的共同朋友,注意判斷順序:

1.直接朋友關係:No problem

2.無任何關係:OK

3.敵對關係(有共同朋友/無共同朋友)  OK but.../No way

AC Code: 

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<string>
#include<cctype>
#include<map>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#define INF 0x3f3f3f3f
using namespace std;
static const int MAX_N = 1e4 + 5;
typedef long long ll;
int pre[105];
int Find(int rt) {
	if (pre[rt] != rt) return Find(pre[rt]);
	return rt;
}
void Join(int a, int b) {
	int rta = Find(a), rtb = Find(b);
	if (rta != rtb) pre[rta] = rtb;
}
int main() {
	int n, m, k;
	int relation[105][105] = { 0 };
	for (int i = 1; i <= 100; i++) pre[i] = i;
	scanf("%d%d%d", &n, &m, &k);
	for (int i = 0; i < m; i++) {
		int a, b, c;
		scanf("%d%d%d", &a, &b, &c);
		relation[a][b] = c;
		relation[b][a] = c;
		if (c == 1) Join(a, b);
	}
	while (k--) {
		int a, b;
		scanf("%d%d", &a, &b);
		if (relation[a][b] == 1) printf("No problem\n");
		else if (relation[a][b] == 0) printf("OK\n");
		else {
			if (Find(a) == Find(b)) printf("OK but...\n");
			else printf("No way\n");
		}
	}
	return 0;
}