CF 129B - Students and Shoelaces

本文介绍了一个简化社交网络中人际关系的算法。通过不断移除只与单个节点相连的节点,直至无法继续移除,以此来减少复杂度。使用C++实现,通过map和set数据结构高效地处理这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

n个人,m对关系。每次能删除当前所有只跟一个人有关系的人,删到不能删要搞多少次。。。map+set不用想什么事,无脑拍就行了。。。

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<stack>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<fstream>
#include<map>
#include<set>
#define FF(i, a, b) for(i=a; i<b; i++)
#define FD(i, a, b) for(i=a; i>b; i--)
#define CLR(a, b) memset(a, b, sizeof(a))
#define LL long long

using namespace std;

int n, m;
map<int, set<int> > s;
set<int> tmp;
set<int> :: iterator iter, it;

int main()
{
    while(~scanf("%d%d", &n, &m))
    {
        s.clear();  
        int a, b, ans = 0, flag = 1;
        while(m--)
        {
            scanf("%d%d", &a, &b);
            s[a].insert(b); s[b].insert(a);
        }
        while(flag)
        {
            flag = 0;   tmp.clear();
            FF(a, 1, n+1)
            {
                int k = s[a].size();
                if(k == 1)
                {
                    flag = 1;
                    tmp.insert(a);
                }
            }
            if(flag)
            {
                for(iter=tmp.begin(); iter!=tmp.end(); iter++)
                {
                    it = s[*iter].begin();
                    s[*it].erase(*iter);
                    s[*iter].clear();
                }
                ans++;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值