[USACO 20OPEN] Favorite Colors G(启发式合并) | 错题本

文章目录

题目

[USACO 20OPEN] Favorite Colors G

分析

按拓扑序枚举各个点,只需要合并把他们的邻接点(即仰慕它的奶牛)合并在一起即可,采用启发式合并。

代码

#include <bits/stdc++.h>

int Read() {
	int x = 0; char c = getchar();
	while (c < '0' || c > '9')
		c = getchar();
	while (c >= '0' && c <= '9')
		x = x * 10 + (c ^ 48), c = getchar();
	return x;
}

const int MAXN = 200000;

int N, M;
int Bel[MAXN + 5], Cnt;
std::queue<int> Q;
std::vector<int> G[MAXN + 5];

int Par[MAXN + 5];
std::vector<int> Son[MAXN + 5];

void Merge(const int &u, const int &v) {
	int x = Par[u], y = Par[v];
	if (Son[y].size() > Son[x].size())
		std::swap(x, y);
	for (int c: Son[y])
		Par[c] = x, Son[x].push_back(c);
	for (int c: G[y])
		G[x].push_back(c);
	if (G[x].size() > 1) Q.push(x);
}

int main() {
	N = Read(), M = Read();
	for (int i = 1; i <= M; i++) {
		int u = Read(), v = Read();
		G[u].push_back(v);
	}
	for (int i = 1; i <= N; i++) {
		Par[i] = i;
		Son[i].push_back(i);
		if (G[i].size() > 1)
			Q.push(i);
	}
	while (!Q.empty()) {
		int u = Q.front(); Q.pop();
		while (G[u].size() > 1) {
			int v = G[u].back(); G[u].pop_back();
			if (Par[v] != Par[G[u].back()])
				Merge(v, G[u].back());
		}
	}
	for (int i = 1; i <= N; i++) {
		if (!Bel[Par[i]])
			Bel[Par[i]] = ++Cnt;
		printf("%d\n", Bel[Par[i]]);
	}
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值