题目读了半天,发现是从1到 2 ~n个点再从 2 ~n个点回到1的最短路。。
所以正向反向分别建图,跑最短路就好了。
#include <algorithm> #include <queue> #include <cstring> #include <iostream> using namespace std; typedef pair<int,int> pa; #define N 1000005 #define inf 0x5f5f5f5f class op{ public: bool operator()(const pa&a,const pa&b){ return a.first>b.first; } }; class graphic{ public: void init(){ cnt = 0; memset(head,-1, sizeof(head)); } void add(int u,int v,int d){ edge[cnt].to = v; edge[cnt].dis = d; edge[cnt].next = head[u]; head[u] = cnt++; } long long deal(int n){ dijkstra(1); long long ans = 0; for(int i = 2 ; i <= n ; ++i){ ans+=dis[i]; } return ans; } private: struct Edge{ int to,next,dis; }edge[N]; int head[N],cnt; int dis[N]; priority_queue <pa,vector<pa>,op>ss; void dijkstra(int beg){ memset(dis,inf, sizeof(dis)); dis[beg] = 0; while (!ss.empty())ss.pop(); ss.emplace(make_pair(dis[0],beg)); while (!ss.empty()){ int u = ss.top().second; ss.pop(); for(int i = head[u] ; ~i ; i = edge[i].next){ if(dis[edge[i].to] > dis[u] + edge[i].dis){ dis[edge[i].to] = dis[u] + edge[i].dis; ss.emplace(make_pair(dis[edge[i].to],edge[i].to)); } } } } }; graphic from,to; int main() { int T; cin>>T; int n,m,u,v,d; while (T--){ cin>>n>>m; from.init(); to.init(); for(int i = 0 ; i < m ; ++i){ scanf("%d %d %d",&u,&v,&d); from.add(u,v,d); to.add(v,u,d); } long long ans = from.deal(n)+to.deal(n); cout<<ans<<" "; } }