博客
关于我
3-2 排座位 (20分)
阅读量:112 次
发布时间:2019-02-26

本文共 1447 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要确保在安排宴席座位时,任何一对死对头不会坐在同一张宴会桌旁。我们可以使用并查集(Union-Find)来高效地管理朋友关系,并使用二维数组来记录敌对关系。

方法思路

  • 初始化数据结构:使用并查集来管理朋友关系,二维数组用于记录敌对关系。
  • 处理关系:遍历所有给定的关系,更新并查集和敌对数组。
  • 处理查询:对于每个查询,检查两位宾客的关系和是否有共同朋友,根据情况输出相应的结果。
  • 解决代码

    #include 
    using namespace std;int f[101];int di[101][101];void init() { for (int i = 1; i <= 100; i++) { f[i] = i; }}int find(int x) { if (x == f[x]) { return x; } else { f[x] = find(f[x]); }}void merge(int x, int y) { int a = find(x); int b = find(y); if (a != b) { f[b] = a; }}int main() { int n, m, k; cin >> n >> m >> k; init(); int g1, g2, ship; while (m--) { cin >> g1 >> g2 >> ship; if (ship == 1) { merge(g1, g2); } else { di[g1][g2] = di[g2][g1] = 1; } } while (k--) { cin >> g1 >> g2; int a = find(g1); int b = find(g2); if (di[g1][g2] == 1) { if (a == b) { cout << "OK but..." << endl; } else { cout << "No way" << endl; } } else { if (a == b) { cout << "No problem" << endl; } else { cout << "OK" << endl; } } } return 0;}

    代码解释

  • 初始化init函数初始化并查集,每个宾客最初都是自己的代表。
  • 查找find函数用于查找一个元素的根节点,路径压缩优化了查找时间。
  • 合并merge函数将两个集合合并,用于处理朋友关系。
  • 处理输入:读取输入数据,处理关系,更新并查集和敌对数组。
  • 处理查询:对于每个查询,检查是否为敌对关系及其共同朋友,输出相应结果。
  • 这种方法确保了高效处理大量关系,并准确判断每对宾客是否可以同席。

    转载地址:http://njdk.baihongyu.com/

    你可能感兴趣的文章
    python 32位和64位的区别在哪
    查看>>
    Python 3:何时使用 dict,何时使用元组列表?
    查看>>
    Python 3d 绘图 - 轴居中
    查看>>
    python ==》 字典
    查看>>
    python anaconda 安装使用
    查看>>
    python and或or 当参数传递的时候的用法
    查看>>
    Python append() 与列表上的 + 运算符,为什么这些会给出不同的结果?
    查看>>
    Python APP自动化测试工具adb与Monkey使用详解
    查看>>
    Python APP自动化测试框架Appium详解
    查看>>
    Python APP自动化测试框架开发实战
    查看>>
    python argparse模块
    查看>>
    Python asyncio库的学习和使用
    查看>>
    Python AttributeError:“dict“对象没有属性“append“
    查看>>
    Python base64和hashlib模块
    查看>>
    python basic programs
    查看>>
    python bert_gen.py 报错Unable to load weights from pytorch checkpoint file for......
    查看>>
    python binascii.Error: Incorrect padding
    查看>>
    Python bool() 函数能否为无效参数引发异常?
    查看>>
    Python C 程序子进程在“for line in iter“处挂起
    查看>>
    Python Celery:自动化测试平台定时任务必备的三方库
    查看>>