P2024 [NOI2001] 食物链 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
最开始没用并查集,用207. 课程表的思路:
- n, k = map(int, input().split(" "))
- res = 0
- dic1 = collections.defaultdict(list)
- dic2 = collections.defaultdict(int)
- for i in range(k):
- x, y, z = map(int, input().split(" "))
- if y > n or z > n:
- res += 1
- continue
- if x == 1:
- dic2[y] = z
- dic2[z] = y
- elif x == 2:
- if dic2[y] == z or dic2[z] == y or y == z:
- res += 1
- elif y in dic1[z]:
- res += 1
- else:
- dic1[y].append(z)
- print(res)
结果只对了两个点
并查集做法:
- import collections
- import sys
- # 读取输入
- input = sys.stdin.readline
- n, k = map(int, input().split())
- # 并查集的初始化
- parent = list(range(3 * n + 1))
- def find(x):
- if parent[x] != x:
- parent[x] = find(parent[x]) # 路径压缩
- return parent[x]
- def union(x, y):
- root_x = find(x)
- root_y = find(y)
- if root_x != root_y:
- parent[root_x] = root_y #找
- res = 0
- for _ in range(k):
- x, y, z = map(int, input().split())
- if y > n or z > n:
- res += 1
- continue
- if x == 1: # 1 X Y 表示 X 和 Y 是同类
- if find(y) == find(z + n) or find(y) == find(z + 2 * n):
- res += 1
- else:
- union(y, z)
- union(y + n, z + n)
- union(y + 2 * n, z + 2 * n)
- elif x == 2: # 2 X Y 表示 X 吃 Y
- if find(y) == find(z) or find(y) == find(z + 2 * n):
- res += 1
- else:
- union(y, z + n)
- union(y + n, z + 2 * n)
- union(y + 2 * n, z)
- print(res)
这两天再研究下