Bellman-Ford算法 循环次数 理解
借助 洛谷 P3371 【模板】单源最短路径(弱化版)在线测评地址https://www.luogu.com.cn/problem/P3371 进行理解
#include <stdio.h>
#define maxm 500010
#define INF 2147483647
#define LL long long
struct node{
int u,v,w;
}e[maxm];
LL d[10010];
int n,m,s;
int main(){
int i,j,check;
scanf("%d%d%d",&n,&m,&s);
for(i=1;i<=m;i++)scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
for(i=1;i<=n;i++)d[i]=INF;
d[s]=0;
for(i=1;i<=n-1;i++){
check=0;
for(j=1;j<=m;j++)
if(d[e[j].v]>d[e[j].u]+e[j].w){
d[e[j].v]=d[e[j].u]+e[j].w;//以边为中转。
check=1;
}
if(!check)break;
}
printf("i=%d n=%d\n",i,n);//若在洛谷P3371提交代码,需将此行注释。
printf("%lld",d[1]);
for(i=2;i<=n;i++)printf(" %lld",d[i]);
printf("\n");
return 0;
}
(1)上述代码对应的数据输入与输出
测试数据根据上图编写
Input:
5 4 1
1 2 1
2 3 1
3 4 1
4 5 1
output:
i=2 n=5
0 1 2 3 4
(2)上述代码对应的数据输入与输出
测试数据根据上图编写
Input:
5 4 1
4 5 1
3 4 1
2 3 1
1 2 1
output:
i=5 n=5
0 1 2 3 4
很明显,对于同一幅图,只是因为边的读取顺序不同,造成了,实际算法时间复杂度的天差地别。
情况(1),循环了2次,情况(2),循环了5-1=4次。
根据情况(2),造了一组卡死Bellman-Ford算法的数据
数据生成程序如下
#include <stdio.h>
int main(){
int n=10000,i;
freopen("data.out","w",stdout);
printf("%d %d 1\n",n,3*(n-1));
for(i=n;i>=2;i--){
printf("%d %d 1\n",i-1,i);
printf("%d %d 1\n",i-1,i);
printf("%d %d 1\n",i-1,i);
}
}
Bellman-Ford算法代码如下
#include <stdio.h>
#include <time.h>
#define maxm 500010
#define INF 2147483647
#define LL long long
struct node{
int u,v,w;
}e[maxm];
LL d[10010];
int n,m,s;
int main(){
int i,j,check;
clock_t st,ed;
double total_t;
st=clock();
scanf("%d%d%d",&n,&m,&s);
for(i=1;i<=m;i++)scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
for(i=1;i<=n;i++)d[i]=INF;
d[s]=0;
for(i=1;i<=n-1;i++){
check=0;
for(j=1;j<=m;j++)
if(d[e[j].v]>d[e[j].u]+e[j].w){
d[e[j].v]=d[e[j].u]+e[j].w;//以边为中转。
check=1;
}
if(!check)break;
}
printf("i=%d n=%d\n",i,n);//若在洛谷P3371提交代码,需将此行注释。
printf("%lld",d[1]);
for(i=2;i<=n;i++)printf(" %lld",d[i]);
printf("\n");
ed=clock();
total_t=(double)(ed-st)/CLOCKS_PER_SEC;
printf("Time used %lfs\n",total_t);
return 0;
}
测试结果,因数据过多,只展示用时部分
Time used 1.061273s
测试数据如下,因篇幅问题,只展示部分数据
10000 29997 1
9999 10000 1
9999 10000 1
9999 10000 1
9998 9999 1
9998 9999 1
9998 9999 1
9997 9998 1
9997 9998 1
9997 9998 1
9996 9997 1
9996 9997 1
9996 9997 1
......
13 14 1
13 14 1
13 14 1
12 13 1
12 13 1
12 13 1
11 12 1
11 12 1
11 12 1
10 11 1
10 11 1
10 11 1
9 10 1
9 10 1
9 10 1
8 9 1
8 9 1
8 9 1
7 8 1
7 8 1
7 8 1
6 7 1
6 7 1
6 7 1
5 6 1
5 6 1
5 6 1
4 5 1
4 5 1
4 5 1
3 4 1
3 4 1
3 4 1
2 3 1
2 3 1
2 3 1
1 2 1
1 2 1
1 2 1