洛谷 P1342 请柬

      洛谷 P1342 请柬

题目描述

在电视时代,没有多少人观看戏剧表演。Malidinesia古董喜剧演员意识到这一事实,他们想宣传剧院,尤其是古色古香的喜剧片。他们已经打印请帖和所有必要的信息和计划。许多学生被雇来分发这些请柬。每个学生志愿者被指定一个确切的公共汽车站,他或她将留在那里一整天,邀请人们参与。

这里的公交系统是非常特殊的:所有的线路都是单向的,连接两个站点。公共汽车离开起始点,到达目的地之后又空车返回起始点。学生每天早上从总部出发,乘公交车到一个预定的站点邀请乘客。每个站点都被安排了一名学生。在一天结束的时候,所有的学生都回到总部。现在需要知道的是,学生所需的公交费用的总和最小是多少。

输入输出格式

输入格式:

第1行有两个整数n、m(1<=n,m<=1000000),n是站点的个数,m是线路的个数。

然后有m行,每行描述一个线路,包括3个整数,起始点,目的地和价格。

总部在第1个站点,价钱都是整数,且小于1000000000

输出格式:

输出一行,表示最小费用。

输入输出样例

输入样例#1: 复制
4 6
1 2 10
2 1 60
1 3 20
3 4 10
2 4 5
4 1 50
输出样例#1: 复制
210 

说明

【注意】

此题数据规模较大,需要使用较为高效的算法,此题不设小规模数据分数。

思路:正反向各建一张图,分别跑spfa,然后将点1到每个点的dis值相加,即为答案

注意:dis值初始化时不要太小;由于题目要求,记得要开long long

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
typedef long long LL;
const int M = 1000005;
const int MAXN = 0x7fffffff;  //注意不要太小 
LL n, m, tot1, tot2, sum;
LL dis1[M], dis2[M], vis1[M], vis2[M];
LL to1[M], net1[M], head1[M], cap1[M];
LL to2[M], net2[M], head2[M], cap2[M];

inline void add1(LL u, LL v, LL w) {
    to1[++tot1] = v; net1[tot1] = head1[u]; head1[u] = tot1; cap1[tot1] = w;
}

inline void add2(LL u, LL v, LL w) {
    to2[++tot2] = v; net2[tot2] = head2[u]; head2[u] = tot2; cap2[tot2] = w;
}

queue<LL> q;
inline void spfa1(LL x) {
    for (LL i = 1; i <= n; ++i) vis1[i] = 0, dis1[i] = MAXN;
    dis1[x] = 0; vis1[x] = 1; q.push(x);
    while (!q.empty()) {
        LL y = q.front(); q.pop(); vis1[y] = 0;
        for (LL i = head1[y]; i; i = net1[i]) {
            LL t = to1[i];
            if (dis1[t] > dis1[y] + cap1[i]) {
                dis1[t] = dis1[y] + cap1[i];
                if (!vis1[t]) vis1[t] = 1, q.push(t);
            }
        }
    }
}

inline void spfa2(LL x) {
    for (LL i = 1; i <= n; ++i) vis2[i] = 0, dis2[i] = MAXN;
    dis2[x] = 0; vis2[x] = 1; q.push(x);
    while (!q.empty()) {
        LL y = q.front(); q.pop(); vis2[y] = 0;
        for (LL i = head2[y]; i; i = net2[i]) {
            LL t = to2[i];
            if (dis2[t] > dis2[y] + cap2[i]) {
                dis2[t] = dis2[y] + cap2[i];
                if (!vis2[t]) vis2[t] = 1, q.push(t);
            }
        }
    }
}

int main() {
    scanf("%lld%lld", &n, &m);
    for(int i = 1; i <= m; ++i) {
        LL a, b, c;
        scanf("%lld%lld%lld", &a, &b, &c);
        add1(a, b, c), add2(b, a, c);  //正反向分别建图 
    }
    spfa1(1), spfa2(1);  //求最短路 
    for(int i = 1; i <= n; ++i)  //求和得到最终答案 
        sum += dis1[i] + dis2[i];
    printf("%lld
", sum);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/v-vip/p/9681763.html