hdu3790 最短路变形

  这题就是比普通的最短路多维护了一个cot数组,cot【i】表示的是起点到i节点的最短路径对应的最小花费。要注意重边的处理,我用邻接表存图,应该是重边没处理好,毕竟邻接表处理重边不太方便要把全部的都遍历一遍,以后有重边的情况还是用邻接矩阵存图算了。

  

#include<bits/stdc++.h>
using namespace std;
#define maxn 1005
#define maxe 100000*2+5
#define inf 0x3f3f3f3f
typedef  long long ll;
struct edge
{
    int v;
    ll w,cost;
    edge(int vv=0,ll ww=0,ll costcost=0)
    {
        v=vv;
        w=ww;
        cost=costcost;
    }
};
ll mp[maxn][maxn],cot[maxn][maxn];
ll dis[maxn],ccos[maxn];
int vis[maxn],n,m,st,et;
void spfa(int v0)
{
    queue<int>q;
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=n;i++)
        ccos[i]=dis[i]=inf;
    dis[v0]=0;
    ccos[v0]=0;//初始化为0,应该起点到其本身的最短距离为0,当然最小花费为0
    q.push(v0);
    vis[v0]=1;
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        vis[u]=0;

        for(int v=1;v<=n;v++)
        {
            ll w=mp[u][v],cost=cot[u][v];
            if(dis[v]>dis[u]+w)
            {
                dis[v]=dis[u]+w;
                ccos[v]=ccos[u]+cost;
                if(!vis[v])
                    q.push(v);
            }
            else
                if((dis[v]==(dis[u]+w))&&(ccos[v]>ccos[u]+cost))
                {
                    ccos[v]=ccos[u]+cost;
                    if(!vis[v])
                        q.push(v);

                }
        }
    }
}


int main()
{
    std::ios::sync_with_stdio(false);
    while(cin>>n>>m)
    {
        if(n==0&&m==0) break;
        memset(mp,0x3f,sizeof(mp));
        memset(cot,0x3f,sizeof(cot));
        for(int i=1;i<=m;i++)
        {
            int u,v;
            ll w,c;
            cin>>u>>v>>w>>c;
            if(w<mp[u][v])
            {
                mp[u][v]=mp[v][u]=w;
                cot[u][v]=cot[v][u]=c;
            }
            else
                if(w==mp[u][v]&&c<cot[u][v])
                {
                    cot[u][v]=cot[v][u]=c;

                }

        }

        cin>>st>>et;
        spfa(st);
        cout<<dis[et]<<" "<<ccos[et]<<endl;
    }


    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40642465/article/details/81323936