HDU.1874 畅通工程续 (Dijkstra)
题意分析
坑点比较多
1. 某两点之间可能有多条通路,在跑Dij时需要用距离最小的算。
2. 当起点和重点相等的时候,距离为0
3. 点的编号从0开始。
代码总览
#include <bits/stdc++.h>
#define nmax 210
using namespace std;
int mp[nmax][nmax];
int dis[nmax];
bool visit[nmax];
int inf = 1e8;
int n,m;
void Dij(int s)
{
int cur = s;
memset(visit,0,sizeof(visit));
visit[cur] = true;
for(int i = 0;i<n;++i) dis[i] = inf;
dis[cur] = 0;
for(int i = 0;i<n;++i){
for(int j = 0; j<n;++j){
if(!visit[j] && dis[cur] + mp[cur][j] < dis[j])
dis[j] = dis[cur] + mp[cur][j];
}
int mini = inf;
for(int j = 0; j<n;++j){
if(!visit[j] && dis[j] < mini){
cur = j;
mini = dis[cur];
}
}
visit[cur] = true;
}
}
int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%d %d",&n,&m) != EOF){
memset(mp,0,sizeof(mp));
for(int i = 0; i<n;++i)
for(int j = 0;j<n;++j)
mp[i][j] = inf;
int sta,end,di;
for(int i = 0;i<m;++i){
scanf("%d %d %d",&sta,&end,&di);
int temp = mp[sta][end];
int ans = min(temp,di);
mp[end][sta] = mp[sta][end] = ans;
}
scanf("%d %d",&sta,&end);
Dij(sta);
if(sta == end){
printf("0
");
}else if(dis[end] == inf){
printf("-1
");
}else{
printf("%d
",dis[end]);
}
}
return 0;
}