Dijkstra(迪杰斯特拉)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<cmath>
#include<vector>
#include<queue>
#include<set>
#include<stack>
#define pi acos(-1)
#define mxan
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define mod 1000000009
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-6
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
#define FRE(i,a,b)  for(i = a; i <= b; i++)
#define FRL(i,a,b)  for(i = a; i < b; i++)
#define mem(t,v)   memset ((t) , v, sizeof(t))
#define sf(n)       scanf("%d", &n)
#define sff(a,b)    scanf("%d %d", &a, &b)
#define sfff(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define pf          printf
using namespace std;
typedef long long ll;
const int N=1e6+5;
const ll IN=1e18;
const int maxn=1020;
int dis[maxn],value[maxn];
int vis[maxn];//记录是否询问

struct edge
{
    int from,to,val,pen;
}h;


struct cmp{
    bool operator()(const edge &a,const edge &b)
    {
        if(a.val!=b.val)
            return a.val>b.val;
        else
            return a.pen>b.pen;
    }
};

int main()
{
    ios::sync_with_stdio(false);
   cin.tie(0);
    int m,n,s,t;
    while(cin>>m>>n)
    {
        if(m==0&&n==0)
            break;
        vector<edge>E[maxn];
        priority_queue<edge,vector<edge>,cmp>Q;
        memset(vis,0,sizeof(vis));
        for(int i=1;i<=m;i++) dis[i]=N*1000;
        for(int i=1;i<=m;i++) value[i]=N*1000;

        for(int i=0;i<n;i++)
        {
            int u,v,w,p;
            cin>>u>>v>>w>>p;
            h.from=u,h.to=v,h.val=w,h.pen=p;
            E[u].push_back(h);
            h.from=v,h.to=u;
            E[v].push_back(h);
        }

        cin>>s>>t;
        dis[s]=0;value[s]=0;
        h.from=s,h.to=s,h.val=0,h.pen=0;
        Q.push(h);
        while(!Q.empty())
        {
            edge x=Q.top();
            Q.pop();
            vis[x.to]=1;
            if(x.to==t)
                break;
            int sz=E[x.to].size();
            for(int i=0;i<sz;i++)
            {
                edge y=E[x.to][i];
                if(vis[y.to])
                continue;
                if(dis[y.to]>dis[x.to]+y.val)
                {
                    dis[y.to]=dis[x.to]+y.val;
                    value[y.to]=value[x.to]+y.pen;
                    h.from=x.to,h.to=y.to,h.val=dis[y.to],h.pen=value[y.to];
                    Q.push(h);
                }
                else if(dis[y.to]==dis[x.to]+y.val&&value[y.to]>value[x.to]+y.pen)
                {
                    dis[y.to]=dis[x.to]+y.val;
                    value[y.to]=value[x.to]+y.pen;
                    h.from=x.to,h.to=y.to,h.val=dis[y.to],h.pen=value[y.to];
                    Q.push(h);
                }
            }
        }
        cout<<dis[t]<<" "<<value[t]<<endl;
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_43870114/article/details/88884215