您的位置:首页 > 其它

hdu 2544 hdu 1874 poj 2387 Dijkstra 模板题

2015-06-18 19:21 127 查看

hdu 2544 

求点1到点n的最短路  无向图

Sample Input
2 1 //结点数 边数
1 2 3 //u v w
3 3
1 2 5
2 3 5
3 1 2
0 0

Sample Output
3
2

 

堆优化Dijstra模板

# include <iostream>
# include <cstdio>
# include <cstring>
# include <algorithm>
# include <cmath>
# define LL long long
using namespace std ;

const int MAXN=1100;
const int INF=0x3f3f3f3f;
int n ;
bool vis[MAXN];
int cost[MAXN][MAXN] ;
int lowcost[MAXN] ;
int pre[MAXN];
void Dijkstra(int beg)
{
for(int i=0;i<n;i++)
{
lowcost[i]=INF;vis[i]=false;pre[i]=-1;
}
lowcost[beg]=0;
for(int j=0;j<n;j++)
{
int k=-1;
int Min=INF;
for(int i=0;i<n;i++)
if(!vis[i]&&lowcost[i]<Min)
{
Min=lowcost[i];
k=i;
}
if(k==-1)
break ;
vis[k]=true;
for(int i=0;i<n;i++)
if(!vis[i]&&lowcost[k]+cost[k][i]<lowcost[i])
{
lowcost[i]=lowcost[k]+cost[k][i];
pre[i]=k;
}
}

}

int main ()
{
// freopen("in.txt","r",stdin) ;
int m ;
while (scanf("%d %d" , &m , &n) !=EOF)
{

int u , v , w ;
int i , j ;
for (i = 0 ; i < n ; i++)
for (j = 0 ; j < n ; j++)
{
if (i == j)
cost[i][j] = 0 ;
else
cost[i][j] = INF ;
}
while(m--)
{
scanf("%d%d%d" , &u , &v , &w) ;
if (w < cost[u-1][v-1]) //防止重边
{
cost[u-1][v-1] = w ;
cost[v-1][u-1] = w ;
}
}
Dijkstra(n-1) ;
if (lowcost[0] != INF)
printf("%d\n" , lowcost[0]) ;

}

return 0 ;
}
View Code

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: