题目链接:http://poj.org/problem?id=1511

思路:题目意思很简单就是要求源点到各点的最短路之和,然后再求各点到源点的最短路之和,其实就是建两个图就ok了,其中一个建反图。1000000个点和1000000条边,一开始用SPFA+vector怎么都是TLE,然后换成邻接表就过了=.=。

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
#define MAXN 1000100
#define inf 1LL<<60 struct Edge{
int v,w,next;
}edge1[MAXN*],edge2[MAXN*]; int head1[MAXN],head2[MAXN];
long long dist[MAXN];
bool mark[MAXN];
int n,m,NE; void Insert(Edge *edge,int *head,int u,int v,int w)
{
edge[NE].v=v;
edge[NE].w=w;
edge[NE].next=head[u];
head[u]=NE;
} long long SPFA(Edge *edge,int *head,int u)
{
memset(mark,false,(n+)*sizeof(bool));
for(int i=;i<=n;i++)dist[i]=inf;
dist[u]=;
queue<int>Q;
Q.push(u);
while(!Q.empty()){
u=Q.front();
Q.pop();
mark[u]=false;
for(int i=head[u];i!=-;i=edge[i].next){
int v=edge[i].v,w=edge[i].w;
if(dist[u]+w<dist[v]){
dist[v]=dist[u]+w;
if(!mark[v]){ mark[v]=true;Q.push(v); }
}
}
}
long long ans=;
for(int i=;i<=n;i++)ans+=dist[i];
return ans;
} int main()
{
int _case,u,v,w;
scanf("%d",&_case);
while(_case--){
scanf("%d%d",&n,&m);
NE=;
memset(head1,-,(n+)*sizeof(int));
memset(head2,-,(n+)*sizeof(int));
while(m--){
scanf("%d%d%d",&u,&v,&w);
Insert(edge1,head1,u,v,w);
Insert(edge2,head2,v,u,w);//建反图
NE++;
}
printf("%lld\n",SPFA(edge1,head1,)+SPFA(edge2,head2,));
}
return ;
}
05-06 19:03