Invitation Cards POJ - 1511

题意:计算从1到各个点的最小花费和从各个点到1的最小花费总和
题解:因数据量太大,不能用Bllmen-Ford,Dijkstra,Floyd算法,故用Spaf算法。和Dijkstra算法有优先队列和队列的区别
注意:计算从各个点到1的最小花费时,可以把路径都倒过来,转变成单源最短路径问题

#include <iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<stack>
#include<queue>
#include <map>
#include<cmath>
#include<vector>
#include <iomanip>
#define MAX_N 1000001
#define INF 0x3f3f3f3f
#define SIZE 1000
#define pai 3.14159265358979323
#define atm 1000000007
using namespace std;
typedef long long LL;
typedef pair<int, int> P;

int n, m;
struct edge
{
    int to;
    int cost;
    edge(int x, int y) : to(x), cost(y){}
};
LL d[MAX_N];
int a[MAX_N], b[MAX_N], c[MAX_N];
vector<edge> G[MAX_N];

void dijkstra()
{
    //priority_queue<P, vector<P>, greater<P> > que;
    queue<P> que;
    for (int i = 0; i <= n; i++)
    {
        d[i] = INF;
    }
    d[1] = 0;
    que.push(P(0, 1));
    while(!que.empty())
    {
        P p = que.front();
        que.pop();
        int v = p.second;
        for (int i = 0; i < G[v].size(); i++)
        {
            edge e = G[v][i];
            if (d[e.to] > d[v] + e.cost)
            {
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to], e.to));
            }
        }
    }
}
void init()
{
    for (int i = 1; i <= n; i++)
    {
        G[i].clear();
    }
}
int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d%d", &n, &m);
        init();
        for (int i = 0; i < m; i++)
        {
            scanf("%d%d%d", &a[i], &b[i], &c[i]);
            //cin >> a[i] >> b[i] >> c[i];
            G[a[i]].push_back(edge(b[i], c[i]));
        }
        dijkstra();
        LL sum = 0;
        for (int i = 1; i <= n; i++)
        {
            sum += d[i];
        }
        init();
        for (int i = 0; i < m; i++)
        {
            G[b[i]].push_back(edge(a[i], c[i]));
        }
        dijkstra();
        for (int i = 1; i <= n; i++)
        {
            sum += d[i];
        }
        cout << sum << endl;
    }
    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值