相比于普通迪杰斯特拉,我们要做的变动是:
优先队列排序
friend bool operator < (const node &f1, const node &f2) {
if(f1.w!=f2.w)
return f1.w > f2.w;
else
return f1.p>f2.p;
}
迪杰斯特拉节点更新
if (dis[end] > dis[start] + edge[i].w) {
dis[end] = dis[start] + edge[i].w;
cost[end]=cost[start]+edge[i].p;
Q.push(edge[i]);
} else if(dis[end]==dis[start]+edge[i].w && cost[end]>cost[start]+edge[i].p) {
cost[end]=cost[start]+edge[i].p;
Q.push(edge[i]);
}
距离更小就更新距离和花费,距离相等就比较花费
#include<cstdio>
#include<iostream>//数组从1开始而不是0
#include<cstring>
#include<queue>
using namespace std;
const int INF=0x3f3f3f3f,N=1e5+10;
struct node {
int to,next,w,p;
friend bool operator < (const node &f1, const node &f2) {
if(f1.w!=f2.w)
return f1.w > f2.w;
else
return f1.p>f2.p;
}
} edge[N];
int n,m,cnt,s,t;
int head[N],dis[N],cost[N];
bool vis[N];
priority_queue<node> Q;
inline void addedge(int from, int to, int w,int p) {
edge[cnt].to = to;
edge[cnt].next = head[from];
edge[cnt].w = w;
edge[cnt].p=p;
head[from] = cnt++;
}
inline void init() {
cnt = 0;
memset(head, -1, sizeof(head));
memset(edge, 0, sizeof(edge));
memset(dis, 0x3f, sizeof(dis));
memset(cost,0x3f,sizeof(cost));
}
void dijkstra(int s,int t) { //s为源点
node z;
z.to=s,z.next=0,z.w=0,z.p=0;
Q.push(z);
dis[s] = 0;
cost[s]=0;
while (Q.size()) {
z = Q.top();
Q.pop();
int start = z.to;
for (int i = head[start]; ~i; i = edge[i].next) {
int end = edge[i].to;
if (dis[end] > dis[start] + edge[i].w) {
dis[end] = dis[start] + edge[i].w;
cost[end]=cost[start]+edge[i].p;
Q.push(edge[i]);
}
else if(dis[end]==dis[start]+edge[i].w && cost[end]>cost[start]+edge[i].p){
cost[end]=cost[start]+edge[i].p;
Q.push(edge[i]);
}
}
}
printf("%d %d\n",dis[t],cost[t]);
}
int main() {
while(~scanf("%d%d",&n,&m)) {
if(n==0 && m==0) return 0;
init();
for (int i = 0; i < m; i++) {
int from, to, w,p;
scanf("%d%d%d%d", &from, &to, &w,&p);
addedge(from, to, w,p);
addedge(to, from, w,p);
}
scanf("%d%d",&s,&t);
dijkstra(s,t);
}
return 0;
}