2010 浙大机试 最短路径问题

题目1008:最短路径问题

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:12200

解决:4184

题目描述:
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
输入:
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点t。n和m为0时输入结束。
(1
输出:
输出 一行有两个数, 最短距离及其花费。
样例输入:
3 2
1 2 5 6
2 3 4 5
1 3
0 0
样例输出:
9 11
代码:dijkstra算法
#include 
#include 
using namespace std;

const int maxn(1e3 + 10);
struct expense{
    int dis;
    int cost;
    expense(int d, int c){
        dis = d;
        cost = c;
    }
    expense(){}
};
inline bool operator < (const expense &one, const expense &another){
    if(one.dis != another.dis){
        return (one.dis < another.dis);
    }
    return (one.cost < another.cost);
}
inline bool operator != (const expense &one, const expense &another){
    return (one.dis != another.dis || one.cost != another.cost);
}
inline expense operator + (const expense one, const expense another){
    return expense(one.dis + another.dis,one.cost + another.cost);
}
const expense INF(expense(0x7fffffff,0x7fffffff));
expense dis[maxn];
bool vis[maxn];
expense matrix[maxn][maxn];
int n, m;
int s, t;
void init();
void dijkstra();
int main(int argc, char const *argv[])
{
    while(scanf("%d %d",&n,&m) != EOF && m && n){
        init();
        int a, b, d, p;
        for(int i = 0; i < m; i++){
            scanf("%d %d %d %d",&a, &b, &d, &p);
            matrix[a][b] = matrix[b][a] = expense(d,p);
        }
        scanf("%d %d",&s,&t);
        dijkstra();
        printf("%d %d\n", dis[t].dis,dis[t].cost);
    }
    return 0;
}
void init()
{
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){
            matrix[i][j] = INF;
        }
        matrix[i][i] = expense(0,0);
        vis[i] = false;
    }
}
void dijkstra()
{
    for(int i = 1; i <= n; i++){
        dis[i] = matrix[s][i];
    }
    int rest = n;
    while(rest && !vis[t]){
        int index;
        expense cur_exp = INF;
        for(int i = 1; i <= n; i++){
            if(!vis[i] && dis[i] < cur_exp){
                cur_exp = dis[i];
                index = i;
            }
        }
        vis[index] = true;
        rest--;
        for(int i = 1; i <= n; i++){
            if(!vis[i] && matrix[index][i] != INF){
                dis[i] = min(dis[i], dis[index] + matrix[index][i]);
            }
        }
    }
}

                                              

你可能感兴趣的:(Dijkstra算法,考研机试题集,考研机试题集)