这是一道最短路,求多点之间的距离,我一开始用的是Floyd,但发现超时了,后来看了大牛的博客才发现一种新的方法,就是设出一个虚点,使这个虚点到要开始点的距离都为0,然后用Dijkstra,具体看代码!
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=1005;
int map[maxn][maxn];
bool p[maxn];
int dist[maxn];
const int inf=0x3f3f3f3f;
int n,m,s;
void init()
{
int i,j;
for(i=0; i<=n; i++)
{
for(j=0; j<=n; j++)
{
map[i][j]=inf;
}
}
}
void Dijkstra()
{
int i,j,pos,min;
for(i=0; i<=n; i++)
{
p[i]=false;
dist[i]=map[0][i];
}
p[0]=true;
dist[0]=0;
for(i=0; i<=n; i++)
{
min=inf;
for(j=0; j<=n; j++)
{
if(!p[j]&&dist[j]<min)
{
min=dist[j];
pos=j;
}
}
p[pos]=true;
for(j=0; j<=n; j++)
{
if(!p[j]&&dist[j]>dist[pos]+map[pos][j])
dist[j]=dist[pos]+map[pos][j];
}
}
}
int main()
{
int i;
while(scanf("%d%d%d",&n,&m,&s)!=EOF)
{
init();
for(i=1; i<=m; i++)
{
int p,q,t;
scanf("%d%d%d",&p,&q,&t);
if(map[p][q]>t)
map[p][q]=t;
}
int a;
scanf("%d",&a);
for(i=1; i<=a; i++)
{
int b;
scanf("%d",&b);
map[0][b]=0;
}
Dijkstra();
if(dist[s]==inf)
printf("-1\n");
else
printf("%d\n",dist[s]);
}
return 0;
}
HDU 2680
最新推荐文章于 2013-11-20 14:16:13 发布