百练1511:Invitation Cards题解

1511:Invitation Cards

题目链接: 点击打开链接

代码:
#include<cstdio>
#include<queue>
#include<cstring>
#include<vector>
using namespace std;
typedef long long ll;
const int N = 1000005;
typedef pair<int, int > PAIR;
struct Edge{
    int to;
    int price;
    int next;
};
Edge G[N],rG[N];
int head1[N],head2[N];
ll dis[N];
void spfa(){
    memset(dis,0x3f,sizeof(dis));
    priority_queue<PAIR, vector<PAIR>, greater<PAIR> > que;
    que.push(PAIR(0,1)); dis[1] = 0;
    while(!que.empty()){
        int u = que.top().second;
        que.pop();
        for(int i = head1[u];i; i = G[i].next){
            Edge e = G[i];
            if(dis[e.to] > dis[u] + e.price){
                dis[e.to] = dis[u] + e.price;
                que.emplace(dis[e.to],e.to);
            }
        }
    }
}
void spfa2(){
    memset(dis,0x3f,sizeof(dis));
    priority_queue<PAIR, vector<PAIR>, greater<PAIR> > que;
    que.push(PAIR(0,1)); dis[1] = 0;
    while(!que.empty()){
        int u = que.top().second;
        que.pop();
        for(int i = head2[u];i; i = rG[i].next){
            Edge e = rG[i];
            if(dis[e.to] > dis[u] + e.price){
                dis[e.to] = dis[u] + e.price;
                que.emplace(dis[e.to],e.to);
            }
        }
    }
}
int main(){
    int n,p,q;
    scanf("%d",&n);
    while(n--){
        memset(head1,0,sizeof(head1));
        memset(head2,0,sizeof(head2));
        scanf("%d%d",&p,&q);
        for(int i = 1; i <= q; ++i){
            int from,to,price;
            scanf("%d%d%d",&from,&to,&price);
            Edge e = {to,price,0};
            G[i] = e;
            G[i].next = head1[from];
            head1[from] = i;
            e.to = from;
            rG[i] = e;
            rG[i].next = head2[to];
            head2[to] = i;
        }
        ll ans = 0;
        spfa();
        for(int i = 2; i <= p; ++i) ans += dis[i];
        spfa2();
        for(int i = 2; i <= p; ++i) ans += dis[i];
        printf("%lld\n", ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值