#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn=1000000+5;
const int inf=100000000;
typedef long long LL;
struct HeapNode{
LL d;
int u;
bool operator < (const HeapNode &rhs) const {
return d>rhs.d;
}
};
struct edge{
int from,to,dist;
};
struct Dijkstra{
int n,m;
vector<edge> edges;
vector<int> G[maxn];
bool done[maxn];
LL d[maxn];
int p[maxn];
void init(int n){
this->n=n;
for(int i=0;i<n;i++) G[i].clear();
edges.clear();
}
void addedge(int from,int to,int dist){
edges.push_back(edge{from,to,dist});
m=(int)edges.size();
G[from].push_back(m-1);
}
void dijkstra(int s){
priority_queue<HeapNode> pq;
for(int i=0;i<n;i++) d[i]=inf;
d[s]=0;
memset(done,0,sizeof(done));
pq.push(HeapNode{0,s});
while(!pq.empty())
{
HeapNode x=pq.top();pq.pop();
int u=x.u;
if(done[u]) continue;
done[u]=true;
for(int i=0;i<G[u].size();i++){
edge &e=edges[G[u][i]];
if(d[e.to]>d[u]+e.dist){
d[e.to]=d[u]+e.dist;
p[e.to]=G[u][i];
pq.push((HeapNode){d[e.to],e.to});
}
}
}
}
};
Dijkstra dij;
int n,m;
int u[maxn],v[maxn],dist[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
dij.init(n);
for(int i=0;i<m;i++){
scanf("%d%d%d",&u[i],&v[i],&dist[i]);
u[i]--;v[i]--;
dij.addedge(u[i],v[i],dist[i]);
}
LL ans=0;
dij.dijkstra(0);
for(int i=0;i<n;i++) ans+=dij.d[i];
dij.init(n);
for(int i=0;i<m;i++) dij.addedge(v[i],u[i],dist[i]);
dij.dijkstra(0);
for(int i=0;i<n;i++) ans+=dij.d[i];
printf("%lld\n",ans);
}
return 0;
}
HDU 1535 Invitation Cards(dijkstra)
最新推荐文章于 2020-05-20 16:50:01 发布