PAT顶级(并查集+BFS)——1014 Circles of Friends (35 分)

1014 Circles of Friends (35 分)


解题思路:

挺无聊一题。。。希望我考试也能遇到这种题啊。。。
就是裸并查集+BFS,用并查集处理朋友圈(学并查集的时候就会了),然后对每个人进行一次BFS,计算他到各个点的最短距离,复杂度挺大,理论上这题应该有更优解,但是who cares,O(N*max(N,E))稳过。
有个坑就是如果计算距离是深度-2的话,输出的时候记得max(0,ans)一下,否则像我一样一直wa

代码:

#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mp make_pair
#define pb push_back
#define G 6.67430*1e-11
#define  rd read()
#define pi 3.1415926535
using namespace std;
const ll mod = 1e9 + 7;
const int MAXN = 30000005;
const int MAX2 = 300005;
inline ll read() {
    ll x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch>'9') {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}
int fa[1005];
int find(int r) { return fa[r] == r ? r : fa[r] = find(fa[r]); }
void join(int x, int y)
{
    int fx = find(x), fy = find(y);
    fa[fx] = fy;
}
int vis[1005], vis2[1005];
vector<int> v[1005];
signed main()
{
    int n = rd;
    for (int i = 1; i <= n; i++)fa[i] = i;
    for (int i = 1; i <= n; i++)
    {
        int k = rd;
        for (int j = 0; j < k; j++)
        {
            int a = rd;
            v[a].push_back(i);
            v[i].push_back(a);
            join(i, a);
        }
    }
    int ma = 0;
    int count = 0;
    for (int i = 1; i <= n; i++)
    {
        if (find(i) == i)count++;
        memset(vis, 0, sizeof vis);
        queue<pii> q;
        q.push(mp(i, 1));
        vis[i] = 1;
        while (q.size())
        {
            auto p = q.front();
            for (int i = 0; i < v[p.first].size(); i++)
            {
                if (!vis[v[p.first][i]])
                {
                    vis[v[p.first][i]] = 1;
                    q.push(mp(v[p.first][i], p.second + 1));
                }
            }
            q.pop();
            if (q.empty())ma = max(ma, p.second);
        }
    }
    cout << count<< ' ' << max(0,ma-2);
    return 0;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值