码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 1511 SPFA+邻接表

时间:2014-12-08 21:04:37      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
#define INF 0xffffffff
#define maxn 1000005

struct Edge
{
    int w, e;
};

int UseCount[maxn], m ,n;
bool Use[maxn];
long long dist[2][maxn];

vector<vector<Edge> > G[2];

void Init()
{
    G[0].clear();
    G[1].clear();
    G[0].resize(n+1);
    G[1].resize(n+1);
    for(int i=1; i<=n; i++)
    {
        dist[1][i] = dist[0][i] = INF, Use[i] = false;
    }
}
long long Spfa(int k)
{
    Edge P, Pn;
    P.w = 0, P.e = 1;
    dist[k][1] = 0;
    queue<Edge>Q;
    Q.push(P);

    while( !Q.empty() )
    {
        P = Q.front();
        Q.pop();
        Use[P.e] = false;
        int len = G[k][P.e].size();

        for(int i=0; i<len; i++)
        {
            Pn = G[k][P.e][i];

            if(dist[k][Pn.e] > dist[k][P.e] + Pn.w)
            {
                dist[k][Pn.e] = dist[k][P.e] + Pn.w;
                if( !Use[Pn.e] )
                {
                    Q.push(Pn);
                    Use[Pn.e] = true;
                }
            }
        }
    }

    long long sum = 0;

    for(int i=1; i<=n; i++)
        sum += dist[k][i];

    return sum;
}

int main()
{
    int T;
    Edge P;
    scanf("%d",&T);
    while(T--)
    {

        scanf("%d%d",&n,&m);
        Init();
        for(int i=0; i<m; i++)
        {
            int a, b, c;
            scanf("%d%d%d",&a,&b,&c);
            P.e = b, P.w = c;
            G[0][a].push_back(P);
            P.e = a;
            G[1][b].push_back(P);
        }
        
        long long sum = 0;
        
        sum += Spfa(0);
        sum += Spfa(1);

        printf("%I64d\n",sum);
    }
    return 0;
}

 

POJ 1511 SPFA+邻接表

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/chenchengxun/p/4151796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!