最短路径问题

最短路径问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

http://acm.hdu.edu.cn/showproblem.php?pid=3790
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年
#include
#include
#include
#include
#include

using namespace std;

const int MAXN = 100000 +5;
const int INF = 0x3f3f3f3f;

struct node{
int from, to, dis, cost;
}edge[MAXN << 1];

int head[MAXN];
int nxt[MAXN << 1];
int dis[MAXN];
bool vis[MAXN];
int cost[MAXN];

int tot = 1;

void add(int u, int v, int d, int c)
{
edge[tot].from = u;
edge[tot].to = v;
edge[tot].dis = d;
edge[tot].cost = c;
nxt[tot] = head[u];
head[u] = tot ++;
}

void init()
{
for(int i = 0; i < MAXN; i ++)
{
head[i] = 0;
dis[i] = INF;
cost[i] = INF;
vis[i] = false;
}
memset(nxt, 0, sizeof(nxt));
tot = 1;
}

void spfa(int s)
{
queue q;
vis[s] = true;
dis[s] = 0;
cost[s] = 0;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i; i = nxt[i])
{
int v = edge[i].to;
if((dis[v] > dis[u] + edge[i].dis) || ((dis[v] == dis[u] + edge[i].dis) && cost[v] > cost[u] + edge[i].cost))
{
dis[v] = dis[u] + edge[i].dis;
cost[v] = cost[u] + edge[i].cost;
if(!vis[v])
{
vis[v] = true;
q.push(v);
}
}
}
}
}

int main()
{
int n, m;
while(scanf("%d%d", &n, &m) != EOF)
{
if(n == 0 && m == 0) break;
init();
int u, v, d, c;
for(int i = 0; i < m; i ++)
{
scanf("%d%d%d%d", &u, &v, &d, &c);
{
add(u, v, d, c);
add(v, u, d, c);
}
}
int s, t;
scanf("%d%d", &s, &t);
spfa(s);
printf("%d %d\n", dis[t], cost[t]);
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值