超时了,求助
查看原帖
超时了,求助
632830
Mark_666楼主2024/7/2 14:39
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int T;
int n,m;
struct Node
{
	int to;
	int next;
}edge[N];
int head[N],tot;
int a[N];
inline void AddCFS(int u,int v)
{
	edge[tot].to=v;
	edge[tot].next=head[u];
	head[u]=tot++;
}
void init()
{
	memset(head,-1,sizeof(head));
	memset(edge,0,sizeof(edge));
	tot=0;
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin>>T;
	while(T--)
	{
		init();
		cin>>n>>m;
		for(int i=1;i<=m;i++)
		{
			int x,y;
			cin>>x>>y;
			AddCFS(x,y);
		}
		for(int i=1;i<=n;i++)
		{
			if(head[i]==-1)
			{
				cout<<'\n';
				continue;
			}
			int x=edge[head[i]].to;
			int y=edge[head[i]].next;
			int cnt=0;
			while(1)
			{
				a[++cnt]=x;
				if(y==-1) break;
				x=edge[y].to;
				y=edge[y].next;
				
			} 
			sort(a+1,a+cnt+1);
			for(int i=1;i<=cnt;i++)
			{
				cout<<a[i]<<' ';
			}
			cout<<'\n';
		}
	}
	return 0;
}

超时1.2s 想练一下链式前向星的,求优化

2024/7/2 14:39
加载中...