您的位置:首页 > 其它

HDOJ 3790 最短路径问题

2016-08-01 19:31 246 查看
最短路径问题
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d
& %I64u
Submit Status

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

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

题意很明显,求两个点之间的最短路径,使用单源最短路的DIJ,数据范围还是蛮大的用vector和优先队列来做,先来理一下思路,求两个点的最短路径,如果最短路径有多条则输出花费最小的,可以看出,判断的时候会加入花费问题,当路径相等时判断花费,先用vector存点和边,把起点压入队列,然后不断的把最小的符合题意的点和边弹出去松弛剩下的点,松弛成功入队,直到队列为空。

#include<algorithm>
#include<stdio.h>
#include<queue>
#include<string.h>
#include<vector>
using namespace std;
#define INF 0x3f3f3f3f
struct node
{
int now;
int len;
int val;
bool operator <(const node &x)const //优先队列的重载小于符号
{
if(len>x.len)
return true;
else if(len<x.len)
return false;
else if(len==x.len)
{
if(val>x.val)
return true;
else
return false;
}
}
};
struct node2 //vector
{
int next;
int len;
int val;
};
priority_queue<node> que;
int main()
{
int n,m;
int dis[1005];
int use[1005];
int v[1005];
int l,r;
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0&&m==0)
break;
while(!que.empty()) //清空队列
que.pop();
for(int i=1;i<=n;i++)
v[i]=dis[i]=INF;
memset(use,0,sizeof(use));
vector<node2>a[1005];
int x,y,z,b;
node2 t;
while(m--)
{
scanf("%d%d%d%d",&x,&y,&z,&b);
t.next=y;
t.len=z;
t.val=b;
a[x].push_back(t);

t.next=x;
t.len=z;
t.val=b;
a[y].push_back(t);
}
scanf("%d%d",&l,&r);
dis[l]=0; //加入起点
v[l]=0;
node temp,next;
temp.len=0;
temp.now=l;
que.push(temp);

while(!que.empty())
{
temp=que.top();
que.pop();
if(use[temp.now]==1)
continue;
use[temp.now]=1;
for(int i=0;i<a[temp.now].size();i++)
{
int now=temp.now;
int templen=dis[now]+a[now][i].len;
int tempval=v[now]+a[now][i].val;
if(dis[a[now][i].next]>templen)
{
dis[a[now][i].next]=templen; //更新
v[a[now][i].next]=tempval;
next.now=a[now][i].next;
next.len=templen;
next.val=tempval;
que.push(next); //入队
}
else if(dis[a[now][i].next]==templen)
{
if(v[a[now][i].next]>tempval)
{
dis[a[now][i].next]=templen;
v[a[now][i].next]=tempval;
next.now=a[now][i].next;
next.len=templen;
next.val=tempval;
que.push(next);
}
}
}
}
printf("%d %d\n",dis[r],v[r]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  最短路