https://www.luogu.com.cn/problem/P2921 n为1005 RE https://www.luogu.com.cn/record/127767460 n为10005MLE https://www.luogu.com.cn/record/127766049
难道要用邻接表写?
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1005;
int isgo[N];
int a[N][N];
int ans = 0;
void dfs(int n)
{
isgo[n] = 1;
for (int i=1;i<=N;i++)
{
if(a[n][i]==1&&isgo[i]==0)
{
ans++;
dfs(i);
}
}
}
int main()
{
int n, t;
memset(a, 0, sizeof(a));
cin >> n;
for (int i=1;i<=n;i++)
{
cin >> t;
a[i][t] = 1;
}
for(int i=1;i<=n;i++)
{
memset(isgo, 0, sizeof(isgo));
ans = 0;
dfs(i);
cout << ans+1 << endl;
}
return 0;
}