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;
}