题解 | 鞋带难题

鞋带难题

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;

}

全部评论

相关推荐

xtu大迫杰:偶遇校友,祝校友offer打牌
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务