2017-09-17 17:37:03
writer:pprp
dijkstra模板题目,注意去重
代码如下:
/*
@theme:poj 2387
@declare:最短路,从N到1点
@writer:pprp
@date:2017/9/17
*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack> using namespace std;
int N, T, Min;
const int maxn = ;
const int INF = 0x3f3f3f3f;
int mp[maxn][maxn];
bool vis[maxn];
int dis[maxn]; void Dijkstra(int st)
{
for(int i = ; i <= N; i++)
{
dis[i] = mp[st][i];
} vis[st] = ;
dis[st] = ; int rec = -;
for(int i = ; i <= N ; i++)//起到了循环的作用
{
Min = INF;
rec = -;
for(int j = ; j <= N; j++)
{
if(!vis[j] && Min > dis[j])
{
rec = j;
Min = dis[j];
}
}
if(rec == -)return ; vis[rec] = ; for(int j = ; j <= N; j++)
{
if(!vis[j] && mp[rec][j] != INF && dis[rec] + mp[rec][j] < dis[j])
dis[j] = mp[rec][j] + dis[rec];
}
}
} int main()
{
freopen("in.txt","r",stdin);
int x, y, v;
cin >> T >> N; for(int i = ; i < maxn; i++)
for(int j = ; j < maxn; j++)
mp[i][j] = INF;
memset(vis,,sizeof(vis)); for(int i = ; i < T ; i++)
{
cin >> x >> y >> v;
if(v < mp[x][y])//去重
mp[x][y] = mp[y][x] = v;
} Dijkstra();
cout << dis[N] << endl; return ;
}