题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3790
今天刷题有点困,就先熟练一下最短路,刷道水题。
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn =1000+5;
const int maxn1 =100000+5;
const int inf =0x3f3f3f3f;
int head[maxn],vis[maxn],dis[maxn],k,s,t,cost[maxn],n,m;
void init()
{
k=0;
memset(head,-1,sizeof(int)*(n+1));
memset(vis,0,sizeof(int)*(n+1));
memset(dis,inf,sizeof(int)*(n+1));
memset(cost,inf,sizeof(int)*(n+1));
}
struct Edge
{
int v,d,p,next;
Edge(){};
Edge(int v1,int d1,int p1,int next1)
{
v=v1,d=d1,p=p1,next=next1;
}
}e[maxn1*2];
void add_edge(int u,int v,int d,int p)
{
e[k]=Edge(v,d,p,head[u]);
head[u]=k++;
e[k]=Edge(u,d,p,head[v]);
head[v]=k++;
}
struct HeapNode//堆优化
{
int d,p,u;
bool operator <(const HeapNode &rhs)const//重载
{
if(d==rhs.d)
return p>rhs.p;//按花费从小到大排
return d >rhs.d;//按距离从小到大排
}
};
void dijkstra()
{
priority_queue<HeapNode> Q;
Q.push((HeapNode){0,0,s});
dis[s]=0;
cost[s]=0;
while(!Q.empty())
{
HeapNode x=Q.top();
Q.pop();
int u=x.u;
if(vis[u])
continue;
vis[u]=1;
for(int i=head[u]; i!=-1; i=e[i].next)
{
int v=e[i].v;
int d=e[i].d;
int p=e[i].p;
if(dis[v]>=dis[u]+d)
{
if(dis[v]==dis[u]+d)
{
if(cost[v]<=cost[u]+p)
continue;
}
dis[v]=dis[u]+d;
cost[v]=cost[u]+p;
Q.push((HeapNode){dis[v],cost[v],v});
}
}
}
return ;
}
int main()
{
while(scanf("%d %d",&n,&m)!=EOF&&(n+m))
{
init();
int a,b,d,c;
for(int i=0; i<m; i++)
{
scanf("%d %d %d %d",&a,&b,&c,&d);
add_edge(a,b,c,d);
}
scanf("%d %d",&s,&t);
dijkstra();
printf("%d %d\n",dis[t],cost[t]);
}
return 0;
}