原题链接
思路:这题问的是将n个人分成res组,且每个组不存在直接上下级关系。所以我们只需要求出每棵树里面最深的深度就是res。 用并查集来求。我用两种方法,状态压缩和不状态压缩都做一遍,由于这题需要求深度,状态压缩是延迟更新 需要在求res之前对所有i都额外一次压缩
//方法一
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2010;
int p[N],d[N];
int find(int x) // 并查集
{
if (p[x] != x)
{
int root = find(p[x]);
d[x]+=d[p[x]];
p[x] = root;
}
return p[x];
}
int main()
{
int n;
cin>>n;
for (int i = 1; i <= n; i ++ )p[i]=i,d[i]=0;
for (int i = 1; i <= n; i ++ )
{
int x;
scanf("%d", &x);
if(x==-1)continue;
int pa=find(i),pb=find(x);
if(pa!=pb)
{
d[i]=d[x]+1;
p[pa]=pb;
}
}
int res=0;
for (int i = 1; i <= n; i ++ )find(i);
for (int i = 1; i <= n; i ++ )
{
res=max(res,d[i]);
}
cout<<res+1;
return 0;
}
//方二
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2010;
int p[N];
int find(int x) // 并查集
{
int deep=1;
while (p[x] != x)
{
x = p[x];
deep++;
}
return deep;
}
int main()
{
int n;
cin>>n;
for (int i = 1; i <= n; i ++ )
{
int x;
scanf("%d", &x);
if(x==-1)p[i]=i;
else p[i]=x;
}
int res=0;
for (int i = 1; i <= n; i ++ )
{
res=max(res,find(i));
}
cout<<res;
return 0;
}