N组数据。给定P个站点,编号1 ~ P,Q条单向路线,每条花费一定金额,现要求从1出发,每个站点都有人,并且最后返回1,求最小金额。
数据很大,邻接矩阵存不下,要用到静态邻接表。静态邻接表存图,spfa正向扫一遍,重组图,让回来时的情况转为从1到各个点的最小金额,同样spfa扫一次。每次spfa后都把各个点的花费加起来,最后的就是答案。(debug了好长时间,( ╯□╰ ))
#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std ;
typedef struct edge {
int now ;
int to ;
int cost ;
} Edge ;
const int inf = 1 << 30 ;
const int MAX = 1000005 ;
int N , P , Q , ans = 0 ;
Edge edge[MAX] ;
int first[MAX] ;
int next[MAX] ;
int dis[MAX] ;
bool had[MAX] ;
queue <int> q ;
void init() {
ans = 0 ;
//memset(edge , -1 , sizeof(edge)) ;
for (int i = 0 ; i <= P ; i ++) {
first[i] = next[i] = -1 ;
}
}
void init_dis(int n) {
memset(had , 0 , sizeof(had)) ;
for (int i = 1 ; i <= P ; i ++) {
dis[i] = inf ;
}
dis[1] = 0 ;
}
void spfa(bool flag) {
q.push(1) ; had[1] = 0 ;
init_dis(1) ;
while (!q.empty()) {
int t = q.front() ; q.pop() ;
had[t] = 0 ;
int to , cost ;
for (int i = first[t] ; i != -1 ; i = next[i]) {
to = (flag? edge[i].to : edge[i].now) ;
cost = edge[i].cost ;
//printf("%d,%d,%d\n",edge[i].now,edge[i].to,edge[i].cost);
//printf("%d,%d,%d\n",i,to,cost);
//printf("%d,%d,%d\n",dis[t],cost,dis[to]);
//cout << "------------\n" ;
if (dis[t] + cost < dis[to]) {
//cout << "1111111111111\n" ;
dis[to] = dis[t] + cost ;
//printf("%d,%d,%d\n",dis[t],cost,dis[to]);
//cout << "------------\n" ;
if (!had[to]) {
had[to] = 1 ;
q.push(to) ;
}
}
}
}
}
void reset() {
for (int i = 0 ; i <= Q ; i ++) {
first[i] = next[i] = -1 ;
}
for (int i = 0 ; i < Q ; i ++) {
next[i] = first[edge[i].to] ;
first[edge[i].to] = i ;
}
}
void print() {
for (int i = 1 ; i <= Q ; i ++) {
//cout << edge[i].now << ',' << edge[i].to << ',' << edge[i].cost << endl ;
//cout << i << ',' << dis[i] << endl ;
cout << next[i] << ',' ;
}
cout << endl ;
for (int i = 1 ; i <= Q ; i ++) {
cout << first[i] << ',' ;
}
cout << endl ;
}
int main() {
//freopen("in.txt" , "r" , stdin) ;
cin >> N ;
while (N --) {
cin >> P >> Q ;
init() ;
for (int i = 0 ; i < Q ; i ++) {
int q1 , q2 , q3 ;
cin >> q1 >> q2 >> q3 ;
edge[i].now = q1 ;
edge[i].to = q2 ;
edge[i].cost = q3 ;
next[i] = first[q1] ;
first[q1] = i ;
}
//print() ;
spfa(1) ;
for (int i = 1 ; i <= P ; i ++) {
//printf("%d,%d\n",i,dis[i]);
ans += dis[i] ;
}
//print() ;
reset() ;
spfa(0) ;
for (int i = 1 ; i <= P ; i ++) {
ans += dis[i] ;
}
//print() ;
cout << ans << endl ;
}
return 0 ;
}