hdu3790——最短路径问题

最短路径问题

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


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 2 1 2 5 6 2 3 4 5 1 3 0 0
 

Sample Output
   
   
   
   
9 11
 

Source
浙大计算机研究生复试上机考试-2010年
 

Recommend
notonlysuccess   |   We have carefully selected several similar problems for you:   2066  1217  2112  1142  2680

最短路,松弛的时候多加一步判断就行

#include <map>
#include <set>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int N = 1010;
const int M = 100010;
const int inf = 0x3f3f3f3f;

int dist[N];
int cost[N];
int head[N];
int tot, n, m;

struct node
{
    int weight;
    int cost;
    int next;
    int to;
}edge[M << 1];

void addedge(int from, int to, int weight, int p)
{
    edge[tot].weight = weight;
    edge[tot].cost = p;
    edge[tot].to = to;
    edge[tot].next = head[from];
    head[from] = tot++;
}

void spfa(int v0)
{
    memset (dist, inf, sizeof(dist));
    memset (cost, inf, sizeof(cost));
    dist[v0] = 0;
    cost[v0] = 0;
    queue <int> qu;
    while (!qu.empty())
    {
        qu.pop();
    }
    qu.push(v0);
    while (!qu.empty())
    {
        int u = qu.front();
        qu.pop();
        for (int i = head[u]; ~i; i = edge[i].next)
        {
            int v = edge[i].to;
            // printf("%d %d\n", dist[v], dist[u] + edge[i].weight);
            if (dist[v] > dist[u] + edge[i].weight)
            {
                dist[v] = dist[u] + edge[i].weight;
                cost[v] = cost[u] + edge[i].cost;
                qu.push(v);
            }
            else if(dist[v] == dist[u] + edge[i].weight && cost[v] > cost[u] + edge[i].cost)
            {
                dist[v] = dist[u] + edge[i].weight;
                cost[v] = cost[u] + edge[i].cost;
                qu.push(v);
            }
        }
    }
}

int main()
{
    int u, v, w, p;
    while (~scanf("%d%d", &n, &m))
    {
        if (!n && !m)
        {
            break;
        }
        memset (head, -1, sizeof(head));
        tot = 0;
        for (int i = 0; i < m; ++i)
        {
            scanf("%d%d%d%d", &u, &v, &w, &p);
            addedge(u, v, w, p);
            addedge(v, u, w, p);
        }
        scanf("%d%d", &u, &v);
        spfa(u);
        printf("%d %d\n", dist[v], cost[v]);
    }
}


 

你可能感兴趣的:(最短路)