首页 > 代码库 > HDU 3790

HDU 3790

最短路径问题

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 14009    Accepted Submission(s): 4304


Problem Description
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
 

 

Input
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
 

 

Output
输出 一行有两个数, 最短距离及其花费。
 

 

Sample Input
3 21 2 5 62 3 4 51 30 0
 

 

Sample Output
9 11

 

加了输入挂,果然快了一倍。然后个人还是不够严谨

 
#include <cstdio>#include <iostream>#include <algorithm>using namespace std;#define N 1010int d[N][N],cost[N][N],vis[N],dist[N],cst[N];int n,m,a,b,dd,p,s,t;const int inf = 0X700000;int in() //输入挂{    int r = 0;    char ch;    ch = getchar();    while(ch < ‘0‘ || ch > ‘9‘) ch = getchar();    while(ch >= ‘0‘ && ch <= ‘9‘)    {        r = r*10 + ch-‘0‘;        ch = getchar();    }    return r;}void init(){    for(int i = 1; i <= n; i++){        for(int j = 1; j <= n; j++)        {            d[i][j] = cost[i][j] = inf;            d[j][i] = cost[j][i] = inf;        }        vis[i] = 0;        dist[i] = cst[i] = inf;    }}void input(){    while(m--)    {        //scanf("%d %d %d %d",&a,&b,&dd, &p);        a = in();        b = in();        dd = in();        p = in();        if(dd < d[a][b]){            d[a][b]= d[b][a] = dd;            cost[a][b] = cost[b][a] = p;        }else if(dd == d[a][b] && p < cost[a][b])        {            cost[a][b] = cost[b][a] = p;        }        //d[a][b] = d[b][a] = min(d[a][b],dd);  这行错误 = =!!果然还是不够严谨        //cost[a][b] = cost[b][a] = min(cost[a][b], p);    }    s = in(); t = in();}void dij(){    for(int i = 1; i <= n; i++){        dist[i] = d[s][i];        cst[i] = cost[s][i];    }    vis[s] = 1;    dist[s] = 0;    cst[s] = 0;    for(int i = 2; i <= n; i++)    {        int mn = inf;        int pos = 1;        for(int j = 1; j <= n; j++)            if(vis[j] == 0 && dist[j] < mn) {pos = j; mn = dist[j];}        vis[pos] = 1;        for(int j = 1; j <= n; j++)        {            if(vis[j] == 0 && d[pos][j] < inf)            {                int newd = dist[pos] + d[pos][j];                int newc = cst[pos] + cost[pos][j];                if(newd < dist[j]) {                        dist[j] = newd;                        cst[j] = newc;                }else if(newd == dist[j] && newc < cst[j])                    cst[j] = newc;            }        }    }}int main(){    while(scanf("%d %d", &n, &m) && (m||n))    {        init();        input();        dij();        printf("%d %d\n", dist[t], cst[t]);    }    return 0;}

  

HDU 3790