HDU 3790 最短路径问题

来源:互联网 发布:网络文体传统文体辩论 编辑:程序博客网 时间:2024/06/06 02:57
最短路径问题
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u

[Submit]  [Go Back]  [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

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

Sample Input

3 21 2 5 62 3 4 51 30 0
 

Sample Output

9 11
 

Source

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


解析

最短路。这个题乍一看两个权值,没什么思路。其实再想想发现,就是把原来的边变成双关键字,相应的dist也变成双关键字就行了。

#include<cstdio>#include<algorithm>#include<queue>#include<cstdio>#include<utility>using namespace std;typedef pair<int,int> pii;struct tnode{tnode* next;int to;pii edge;};typedef tnode* pnode;pnode Chain[1010];int N,M,w[1010],vis[1010],S,T;pii dist[1010];void insert(int from,int to,int len,int weight){pnode p=new tnode;p->next=Chain[from];p->to=to;p->edge=make_pair(len,weight);Chain[from]=p;}void readdata(){for(int i=1;i<=N;i++) Chain[i]=NULL;for(int i=1;i<=M;i++){int a,b,len,weight;scanf("%d%d%d%d",&a,&b,&len,&weight);insert(a,b,len,weight); insert(b,a,len,weight);}scanf("%d%d",&S,&T);}inline pii add(pii a,pii b) {return make_pair(a.first+b.first,a.second+b.second);}void spfa(){memset(vis,0,sizeof(vis)); vis[S]=1;memset(dist,0x3f,sizeof(dist)); dist[S]=make_pair(0,0);queue<int> q;q.push(S);while(!q.empty()){int u=q.front(); q.pop(); vis[u]=0;for(pnode p=Chain[u];p;p=p->next)if(dist[p->to]>add(dist[u],p->edge)){dist[p->to]=add(dist[u],p->edge);if(!vis[p->to]){vis[p->to]=1; q.push(p->to);}}}printf("%d %d\n",dist[T].first,dist[T].second);//printf("\n"); for(int i=1;i<=N;i++) printf("%d %d\n",dist[i].first,dist[i].second);}int main(){//freopen("hdu3790.in","r",stdin);while(scanf("%d%d",&N,&M)==2){if(N==0) break;readdata();spfa();}while(1);return 0;}


0 0