bfs,链表前向星,循环数组作队列,但是全TLE
查看原帖
bfs,链表前向星,循环数组作队列,但是全TLE
584974
Fecser_617楼主2023/5/24 08:31

整整跑了6秒,代码如下

#include <bits/stdc++.h>
using namespace std;
int p[1000010],l=0,r=1;//循环数组当队列 
int n,m;
int to[4000010],nex[4000010],fir[1000010],cnt=0;
int vis[1000010]={1,1},ans[1000010]={0,1},dis[1000010];
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++){
		int a,b;
		scanf("%d%d",&a,&b);
		if(a==b)continue; 
		++cnt;//第++cnt条边 
		to[cnt]=b;//这条边到b
		nex[cnt]=fir[a];//这条边下一条到fir[a]
		fir[a]=cnt;//记录 
		
		++cnt;//第++cnt条边 
		to[cnt]=a;//这条边到b
		nex[cnt]=fir[b];//这条边下一条到fir[a]
		fir[b]=cnt;//记录 
	}
	p[r]=1;//从1开始遍历
	vis[1]=1;
	while(l!=r){//即队列内存在数字 
		l=(l++)%1000010;//l到下一位有数字的 
		int temp=p[l];//取出该位数字
		for(int tmp=fir[p[l]];tmp;tmp=nex[tmp]){
			if(!vis[to[tmp]]){//没被遍历
				vis[to[tmp]]=1;
				dis[to[tmp]]=dis[temp]+1;//记录距离 
				r=(r+1)%1000010;
				p[++r]=to[tmp];//放入队列 
			}
			if(dis[temp]+1==dis[to[tmp]]){
				ans[to[tmp]]=(ans[to[tmp]]+ans[temp])%100003;//最小路条数加上个答案 
			}
		}
	}
	for(int i=1;i<=n;i++){
		printf("%d\n",ans[i]);
	} 
	
	return 0;
}

谁能猜到问题出在了那个"l=(l++)%1000010;"改成了"l=(l+1)%1000010;"或者"l++;l%=1000010;"就可以AC了,所以用来给大家一个反面教材,千万别犯这种看着都离谱的错。

2023/5/24 08:31
加载中...