L2-010 排座位 (25 分)
布置宴席最微妙的事情,就是给前来参宴的各位宾客安排座位。无论如何,总不能把两个死对头排到同一张宴会桌旁!这个艰巨任务现在就交给你,对任何一对客人,请编写程序告诉主人他们是否能被安排同席。
输入格式:
输入第一行给出3个正整数:N
(≤100),即前来参宴的宾客总人数,则这些人从1到N
编号;M
为已知两两宾客之间的关系数;K
为查询的条数。随后M
行,每行给出一对宾客之间的关系,格式为:宾客1 宾客2 关系
,其中关系
为1表示是朋友,-1表示是死对头。注意两个人不可能既是朋友又是敌人。最后K
行,每行给出一对需要查询的宾客编号。
这里假设朋友的朋友也是朋友。但敌人的敌人并不一定就是朋友,朋友的敌人也不一定是敌人。只有单纯直接的敌对关系才是绝对不能同席的。
输出格式:
对每个查询输出一行结果:如果两位宾客之间是朋友,且没有敌对关系,则输出No problem
;如果他们之间并不是朋友,但也不敌对,则输出OK
;如果他们之间有敌对,然而也有共同的朋友,则输出OK but...
;如果他们之间只有敌对关系,则输出No way
。
输入样例:
in
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
输出样例:
out
No problem
OK
OK but...
No way
分析
做题步骤
- 基础并查集。
- 判断是否为敌对关系。
各情况输出表
朋友 | 死对头 | 输出 |
---|---|---|
1 | 1 | OK but… |
1 | 0 | No problem |
0 | 1 | No way |
0 | 0 | OK |
朴素并查集模板
int p[N]; //存储每个点的祖宗节点
// 返回x的祖宗节点
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
// 初始化,假定节点编号是1~n
for (int i = 1; i <= n; i ++ ) p[i] = i;
// 合并a和b所在的两个集合:
p[find(a)] = find(b);
代码
#include <bits/stdc++.h>
using namespace std;
int n,m,k, p[1005]; //p[]存储每个点的祖宗节点
bool b[1000][1000];
//返回x的祖宗节点
int find(int x)
{
/* 包含路径压缩
if (p[x] != x)
p[x] = find(p[x]);
return p[x];
*/
// 没有路径压缩
if (p[x] != x)
return find(p[x]);
else return p[x];
}
int main()
{
int x,l,r;
cin >> n>>m>>k;
// 初始化,假定节点编号是1~n
for (int i = 0; i <= n; i++) p[i]=i;
while(m--){
cin>>l>>r>>x;
if (x==1)
p[find(l)] = find(r); // 合并a和b所在的两个集合:
else b[l][r]=true;
}
while (k--)
{
cin>>l>>r;
if (find(l) == find(r))
{
if (b[l][r]==true||b[r][l]==true){
cout << "OK but..."<<endl;
}
else
cout << "No problem" << endl;
}
else if (b[l][r] == true || b[r][l] == true)
{
cout << "No way" << endl;
}
else
cout << "OK" << endl;
}
return 0;
}
//多加一个树高height[]
//小树接到大树下,同时height[l]=max(height[l],height[r]+1);
// 下面的代码还没改完!
#include <bits/stdc++.h>
using namespace std;
int n,m,k, p[1005],height[1005];
bool b[1000][1000];
int find(int x)
{
if (p[x] != x)
p[x] = find(p[x]);
return p[x];
}
int main()
{
int x,l,r;
cin >> n>>m>>k;
for (int i = 0; i <= n; i++) p[i]=i;
while(m--){
cin>>l>>r>>x;
if (x==1) p[find(l)] = find(r);
else b[l][r]=true;
}
while (k--)
{
cin>>l>>r;
if (find(l) == find(r))
{
if (b[l][r]==true||b[r][l]==true){
cout << "OK but..."<<endl;
}
else
cout << "No problem" << endl;
}
else if (b[l][r] == true || b[r][l] == true)
{
cout << "No way" << endl;
}
else
cout << "OK" << endl;
}
return 0;
}
《常用代码模板2——数据结构》 . yxc . https://www.acwing.com/blog/content/404/