题目链接<http://poj.org/problem?id=1511>
题意:
一群人从1号点出发,前往各个点(每个点都有一个人去),然后又到一号点。所有的点通过一系列的单向边连接,问需要的时间最少是多少。
题解:
用链式前向星的话需要设置两个图,一个图是正常的图,另一个图起始点与终点相反。对两张图进行1号点到各个点的dij,累加即可。
注意:wa的话改成longlong
#include <iostream>
#include <cstdio>
#include <map>
#include <queue>
#include <string.h>
#include <string>
using namespace std;
typedef long long LL;
struct Edge{
LL to,val,next;
Edge(LL to=0,LL val=0,LL next=0):to(to),val(val),next(next){}
}e[2][1000005];
LL head[2][1000005],now0,now1;
void add(LL a,LL b,double c){
e[0][++now0]=Edge(b,c,head[0][a]);head[0][a]=now0;
e[1][++now1]=Edge(a,c,head[1][b]);head[1][b]=now1;
}
struct Node{
LL id,val;
bool operator<(const Node a)const{
return this->val>a.val;
}
Node(LL id,LL val):id(id),val(val){}
};
LL n,m;
LL dis[2][1000005],vis[1000005];
void dij(LL x){
priority_queue<Node>q;
q.push(Node(1,0));
memset(dis[x],125,sizeof(dis[x]));
memset(vis,0,sizeof(vis));
dis[x][1]=0;
while(!q.empty()){
Node t=q.top();q.pop();
LL u=t.id;
vis[u]=1;
for(LL i=head[x][u];~i;i=e[x][i].next){
LL v=e[x][i].to;
if(!vis[v]&&dis[x][v]-dis[x][u]>e[x][i].val){
dis[x][v]=dis[x][u]+e[x][i].val;
q.push(Node(v,dis[x][v]));
}
}
}
}
int main(){
LL t;
scanf("%lld",&t);
while(t--){
scanf("%lld%lld",&n,&m);
now0=now1=-1;memset(head,-1,sizeof(head));
LL u,v,w;
for(LL i=1;i<=m;i++){
scanf("%lld%lld%lld",&u,&v,&w);
add(u,v,w);
}
dij(0);dij(1);
LL ans=0;
for(LL i=1;i<=n;i++){
ans+=dis[0][i]+dis[1][i];
}
printf("%lld\n",ans);
}
}