#include <functional>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#include <set>
#include <vector>
using namespace std ;
typedef long long LL;
#define pii pair <LL, int>
const int N=1000050;
bool vis[N];
int tot,tot2;
LL dis[N];
struct node
{
LL w;
int next;
int to;
} edge[N+10],edge2[N+10];
int head[N],head2[N+10];
void addedge(int from,int to,LL w,node edge[],int head[],int &tot)
{
edge[tot].w=w;
edge[tot].to=to;
edge[tot].next=head[from];
head[from]=tot++;
}
LL dijkstra(int s,int n,int head[],node edge[])
{
memset(dis,0x3f3f3f3f,sizeof dis);
dis[s]=0;
priority_queue<pii,vector<pii>,greater<pii> >q;
while(!q.empty())
{
q.pop();
}
q.push(make_pair(dis[s],s));
while(!q.empty())
{
pii tmp=q.top();
q.pop();
int u=tmp.second;
LL d=tmp.first;
for(int i=head[u]; ~i; i=edge[i].next)
{
int v=edge[i].to;
if(dis[v]>edge[i].w+d)
{
dis[v]=edge[i].w+d;
q.push(make_pair(dis[v],v));
}
}
}
LL ans=0;
for(int i=1; i<=n; i++)
{
ans+=dis[i];
}
return ans;
}
int main ()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m;
scanf("%d%d",&n,&m);
memset (head, -1, sizeof(head));
memset (head2, -1, sizeof(head2));
tot = tot2 = 0;
int u, v;
LL w;
for (int i = 1; i <= m; ++i)
{
scanf("%d%d%lld", &u, &v, &w);
addedge (u, v, w, edge, head, tot);
addedge (v, u, w, edge2, head2, tot2);
}
LL ans = dijkstra (1, n, head, edge);
ans += dijkstra (1, n, head2, edge2);
printf("%lld\n", ans);
}
return 0 ;
}
【POJ1511】Invitation Cards 【dijkstra+优先队列+邻接表】
最新推荐文章于 2019-08-15 15:24:58 发布