hdu 1874 最短路

enmmmmm  题意 直接就是最短路 , 有一个需要注意的就是 两点之间的边不止一条

dijstra 算法

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#define inf 0x7ffffff
#define MAXN 0x3f3f3f3f
const int INF = 0x3f3f3f3f;
using namespace std;
int n,x,y,m,ed,sss,v[1010],d[1010],w[1010][1010];
void dijstra(int sss) {
    fill(v,v+n,0);
    for(int i = 0; i < 300; i++) d[i] = INF;//memset(d,0x3f,sizeof(d));
    d[sss] = 0;
    for(int i = 0; i < n; i++) {
        int x,m=INF;
        for(int y = 0; y < n; y++) if(!v[y] && d[y]<=m) m = d[x=y];
        v[x] = 1;
        for(int y = 0; y < n; y++) d[y] = std::min(d[y],d[x]+w[x][y]);
    }
}//N和M(0<N<200,0<M<1000)
int main() {
    while(scanf("%d%d",&n,&m) == 2) {//memset(a,0x3f,sizeof(a))
        for(int i = 0; i < 300; i++)for(int j = 0; j < 300; j++)w[i][j] = (i==j?0:INF);
        for(int i = 0; i < m; i++) {
            scanf("%d%d%d", &x, &y, &ed);
            w[x][y] = min(ed,w[x][y]);
            w[y][x] = min(ed,w[y][x]);
        }
        scanf("%d%d", &x, &y);
        dijstra(x);
        printf("%d\n", d[y]<INF?d[y]:-1);
    }
    return 0;
}
/*
Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
Sample Output
2
-1
*/
View Code

 

floyd 算法

#include <cstdio>
#include <iostream>
#define INF 100000
#define inf 0x7ffffff
#define MAXN 0x3f3f3f3f
int dis[220][220];
int main(){
    int n,m;
    while(scanf("%d%d",&n,&m) == 2)
    {
        int a,b,c;
        //memset(mat,0x3f,sizeof(mat));
        //for(int i=0;i<n;i++) mat[i][i]=0;
        for (int i = 0; i < 220; i++)
            for (int j = 0; j < 220; j++)
                dis[i][j] = (i == j)?0:INF;
            
        for (int i = 0; i < m; i++)
            {
                scanf("%d%d%d", &a, &b, &c);
                //a--;b--;
                c = std::min(c,dis[a][b]);//加了句这个???? 6了 两个城间有一堆路的意思。
                dis[a][b] = c;
                dis[b][a] = c;
            }

        for (int k = 0; k < n; k++)
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                    if (dis[i][k]+dis[k][j] < dis[i][j])
                            dis[i][j] = dis[i][k]+dis[k][j];

        scanf("%d%d", &a, &b);//a--;b--;
        c = dis[a][b];
        if(c == INF) c = -1;
        printf("%d\n", c);
    }return 0;
}
/*
Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
Sample Output
2
-1
*/
View Code

 

posted @ 2018-12-06 21:07  163467  阅读(106)  评论(0)    收藏  举报