求助,图的遍历
  • 板块学术版
  • 楼主TARGETMINE
  • 当前回复3
  • 已保存回复3
  • 发布时间2023/10/5 15:55
  • 上次更新2023/11/2 15:29:40
查看原帖
求助,图的遍历
935263
TARGETMINE楼主2023/10/5 15:55

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;
}
2023/10/5 15:55
加载中...