您的位置:首页 > 其它

hdu 1874畅通工程续= =

2016-03-22 19:24 381 查看
Dijkstra:
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int book[205];
int dis[205];
int map[205][205];
int n , m , a,b,x,s,t,mind,po;
const int inf = 9999999;
int d(int s){
memset(book,0,sizeof(book));
book[s] = 1;
for(int i = 0;i < n; i++)
dis[i] = map[s][i];
for(int i = 0;i < n; i++){
mind = inf;           每次找离出发点最近的点
for(int j = 0;j < n; j++){
if(dis[j]<mind&&!book[j]){
mind = dis[j];
po = j;
}
}
book[po] = 1;  标记走过该点
for(int i = 0;i < n; i++){
if(dis[i]>dis[po]+map[po][i])
dis[i]=dis[po]+map[po][i];
}
}
return dis[t];
}
int main(int argc, char *argv[]) {
while(cin>>n>>m){
for(int i = 0;i < n; i++){
for(int j = 0;j < n; j++){
if(i==j)map[i][j] = 0;
else map[i][j] = inf;
}
}
for(int i = 1;i <= m; i++){
cin>>a>>b>>x;
if(x<map[a][b]){//这地方wa了好多次。。唉,,
map[a][b] = x;
map[b][a] = x;
}
}
for(int i = 0;i < n; i++)
dis[i] = inf;
cin>>s>>t;
if(d(s)==inf)
cout<<“-1”<<endl;
else cout<<dis[t]<<endl;

}
return 0;
}
Floyd¡ªwarshall 这个算法貌似更简单。。
 #include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int map[205][205];
const int inf = 999999;
int main(int argc, char *argv[]) {
    int n,m,i,j,k,a,b,c,st,end;
    while(cin>>n>>m){
        for(int i = 0;i < n; i++){
            for(int j = 0;j < n; j++){
                if(i==j)map[i][j] = 0;
                else map[i][j] = inf;
            }
        }
       for(int i = 0;i < m ;i++)
        {
          cin>>a>>b>>c;
          if(map[a][b]>c){
          map[a][b] = c;
          map[b][a] = c;
      }
        }
       for(int k = 0;k < n; k++){        检验i、j点借助k点能否缩短它们间的距离
           for(int i = 0;i < n; i++){
               for(int j = 0;j < n; j++){
                   if(map[i][j]>map[i][k]+map[k][j])
                   map[i][j]=map[i][k]+map[k][j];
               }
           }
       }    
       cin>>st>>end;
       if(map[st][end]==inf)cout<<"-1"<<endl;
       else cout<<map[st][end]<<endl;
    }
    return 0;
}

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