Invitation Cards POJ - 1511 spfa

//从起点1到剩余P-1个点的最短距离之和+从剩余P-1个点到起点1的最短距离之和
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int LEN=1000005;
const int INF=0x3f3f3f3f;
struct Edge{
    int to, next;
    long long val;
}edge[2][LEN];
int h[2][LEN], cnt1, cnt2;
int p, q;
long long dis[LEN];
bool vis[LEN];
void spfa(int cnt)
{
    queue<int>q;
    memset(dis,INF,LEN*sizeof(long long));
    memset(vis,false,LEN *sizeof(bool));
    dis[1]=0;
    q.push(1);
    vis[1]=true;
    while(!q.empty())
    {
        int x;
        x=q.front();
        q.pop();
        vis[x]=false;
        for(int k=h[cnt][x];k!=-1;k=edge[cnt][k].next)
        {
            int y=edge[cnt][k].to;
            if(dis[x]+edge[cnt][k].val<dis[y])
            {
                dis[y]=dis[x]+edge[cnt][k].val;
                if(!vis[y])
                {
                    vis[y]=true;
                    q.push(y);
                }
            }
        }
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    while(n--)
    {
        cnt1=cnt2=1;
        scanf("%d%d",&p,&q);
        int beg,end;
        long long val;
        memset(h,-1,sizeof h);
        for(int i=0; i<q;i++ )
        {
            scanf("%d%d%lld",&beg,&end,&val);
            //正向建图 
            edge[0][cnt1].to=end;
            edge[0][cnt1].val=val;
            edge[0][cnt1].next=h[0][beg];
            h[0][beg]=cnt1++;
            //反向建图 
            edge[1][cnt2].to=beg;
            edge[1][cnt2].val=val;
            edge[1][cnt2].next=h[1][end];
            h[1][end]=cnt2++;
        }
        long long ans=0;
        spfa(0);
        for(int i=1;i<=p;i++) 
            ans+=dis[i];
        spfa(1);
        for(int i=1;i<=p;i++) 
            ans+=dis[i];
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/QingyuYYYYY/p/12235916.html