题解 ABC293D【Tying Rope】

颜色是不好处理的,我们不妨不区分绳子的两个端点,将每条绳子作为一个节点,每条边直接将两个节点连接起来。每个绳子的端点本质上是保证了每个点的度数不超过 \(2\),也就是说图的每个连通块要么是环要么是链。题目即统计有多少个环、多少个链。

洪水填充统计每个连通块的点数、边数即可。

时间复杂度 \(\mathcal O(n+m)\)

// Problem: D - Tying Rope
// Contest: AtCoder - AtCoder Beginner Contest 293
// URL: https://atcoder.jp/contests/abc293/tasks/abc293_d
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

//By: OIer rui_er
#include <bits/stdc++.h>
#define rep(x,y,z) for(int x=(y);x<=(z);x++)
#define per(x,y,z) for(int x=(y);x>=(z);x--)
#define debug(format...) fprintf(stderr, format)
#define fileIO(s) do{freopen(s".in","r",stdin);freopen(s".out","w",stdout);}while(false)
#define likely(exp) __builtin_expect(!!(exp), 1)
#define unlikely(exp) __builtin_expect(!!(exp), 0)
using namespace std;
typedef long long ll;

mt19937 rnd(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
int randint(int L, int R) {
	uniform_int_distribution<int> dist(L, R);
	return dist(rnd);
}

template<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}
template<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}

const int N = 2e5+5;

int n, m, vis[N], cntV, cntE, ansA, ansB;
vector<int> e[N];

void dfs(int u) {
	vis[u] = 1;
	++cntV;
	for(int v : e[u]) {
		if(!vis[v]) dfs(v);
		++cntE;
	}
}

int main() {
	scanf("%d%d", &n, &m);
	rep(i, 1, m) {
		int u, v; char s[2], t[2];
		scanf("%d%s%d%s", &u, s, &v, t);
		e[u].push_back(v);
		e[v].push_back(u);
	}
	rep(i, 1, n) {
		if(!vis[i]) {
			cntV = cntE = 0;
			dfs(i);
			cntE >>= 1;
			if(cntV == cntE) ++ansA;
			else ++ansB;
		}
	}
	printf("%d %d\n", ansA, ansB);
	return 0;
}
posted @ 2023-03-12 08:26  rui_er  阅读(46)  评论(0编辑  收藏  举报