题解 | 鞋带难题
鞋带难题
https://www.nowcoder.com/practice/04238c060cce4e14a9e2d885836174c0
#include <iostream>
#include <vector>
#include <queue>
#include <set>
using namespace std;
const int N = 1e5 + 5;
int n, m;
int t[N];
vector<int> g[N];
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
t[a]++;
t[b]++;
}
queue<int> q;
for (int i = 1; i <= n; i++) {
if (t[i] == 1) {
q.push(i);
}
}
int ans = 0;
while (q.size()) {
ans++;
int sz = q.size();
set<int> s;
while (sz--) {
int x = q.front();
q.pop();
for (int i = 0; i < g[x].size(); i++) {
int y = g[x][i];
s.insert(y);
t[y]--;
}
}
for (int y : s) {
if (t[y] == 1) {
q.push(y);
}
}
}
cout << ans;
}
查看19道真题和解析