Official

D - Tying Rope Editorial by en_translator


Consider the \(N\) ropes as \(N\) vertices of a graph, and connecting ropes \(a\) and \(b\) as an edge connecting vertices \(a\) and \(b\); then the problem is rephrased as follows.

  • You are given a graph with \(N\) vertices and \(M\) edges. The \(i\)-th edge connects vertices \(A_i\) and \(C_i\). Every vertex has a degree at most two. Each component is either a cycle or a path; how many cycles and paths are there?

A connected component is a cycle if and only if the degree of every vertex is two, so one can store the degree of each vertex and check if each connected component forms a cycle with BFS (Breadth-First Search) for example; this way, the problem has been solved in a total of \(O(N+M)\) time.

Sample code

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int main() {
	int n, m;
	cin >> n >> m;
	vector<vector<int>> graph(n, vector<int>());
	vector<int> deg(n);
	for (int i = 0; i < m; i++) {
		int a, c;
		char b, d;
		cin >> a >> b >> c >> d;
		a--; c--;
		graph[a].push_back(c);
		graph[c].push_back(a);
		deg[a]++; deg[c]++;
	}
	int x = 0, y = 0;
	vector<bool> used(n);
	for (int i = 0; i < n; i++) {
		if (!used[i]) {
			queue<int> que;
			used[i] = true;
			que.push(i);
			bool f = true;
			while (!que.empty()) {
				int q = que.front(); que.pop();
				if (deg[q] != 2) f = false;
				for (int v : graph[q]) {
					if (!used[v]) {
						que.push(v);
						used[v] = true;
					}
				}
			}
			if (f) x++;
			else y++;
		}
	}
	cout << x << ' ' << y << '\n';
}

posted:
last update: