就不写题目链接了
Sample Input
5 5 点个数a,边个数b
1 2 20 点,点,权值
2 3 30
3 4 20
4 5 20
1 5 100
求出1到a的最短距离
Sample Output
90
防止有重边
#include <iostream>
#include <cstdio>
using namespace std;
#define Max 1000+10
#define INF 0x3f3f3f3f
int cost[Max][Max];
int lowcost[Max];
bool vis[Max];
int N,T;
void dijkstra(int s)
{ int i,u,v;
for(u=;u<=N;u++)
{
lowcost[u]=INF;
vis[u]=;
}
lowcost[]=;
int Min=INF; while()
{
int p=-;
for(u=;u<=N;u++)
{
if(!vis[u]&&(p==-||lowcost[u]<lowcost[p]))
p=u;
}
if(p==-) break;
vis[p]=;
for(u=;u<=N;u++)
if(!vis[u]&&(lowcost[p]+cost[p][u])<lowcost[u])
lowcost[u]=lowcost[p]+cost[p][u];
}
}
int main()
{
int i,j;
int a,b,w;
freopen("in.txt","r",stdin);
while(scanf("%d%d",&T,&N)!=EOF)
{
for(i=;i<=N;i++)
{
for(j=;j<=N;j++)
{
if(j==i)
cost[i][j]=;
else
cost[i][j]=cost[j][i]=INF;
}
}
for(i=;i<T;i++)
{
scanf("%d%d%d",&a,&b,&w);
if(w<cost[a][b])
{
cost[a][b]=cost[b][a]=w;
}
}
dijkstra();
printf("%d\n",lowcost[N]);
}
}
Sample Input
3 3 点,边数
0 1 1 边
0 2 3
1 2 1
0 2 起点,终点
3 1
0 1 1
1 2
Sample Output
2
1
#include <iostream>
#include <cstdio>
using namespace std;
#define Max 200+10
#define INF 0x3f3f3f3f
int cost[Max][Max];
int lowcost[Max];
bool vis[Max];
int N,M;
void dijkstra(int s)
{
int u,i,p;
for(u=;u<N;u++)
{
vis[u]=;
lowcost[u]=INF;
}
lowcost[s]=;
while()
{
p=-;
for(u=;u<N;u++)
if(!vis[u]&&(p==-||lowcost[u]<lowcost[p]))
p=u;
if(p==-) break;
vis[p]=;
for(u=;u<N;u++)
if(!vis[u]&&(lowcost[p]+cost[u][p])<lowcost[u])
lowcost[u]=lowcost[p]+cost[u][p];
}
}
int main()
{
int i,j;
int a,b,w,s,e;
freopen("in.txt","r",stdin);
while(~scanf("%d%d",&N,&M))
{ for(i=;i<N;i++)
for(j=;j<N;j++)
if(i==j) cost[i][j]=cost[j][i]=;
else cost[i][j]=cost[j][i]=INF; for(i=;i<M;i++)
{
scanf("%d%d%d",&a,&b,&w);
if(w<cost[a][b]) cost[a][b]=cost[b][a]=w; /*解决重边*/
}
scanf("%d%d",&s,&e);
dijkstra(s);
if(lowcost[e]==INF)
printf("-1\n");
else
printf("%d\n",lowcost[e]);
}
}