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;
}