这是我用邻接表过得第一道题;不得不说最开始参考了网上大神的代码;花了一晚上终于明白了邻接表的用法;head[s]代表的是入点为S的边标号,而edge.next记录的是下一条入点为s的边的标号;
然后就是水水的SPFA了,求两次就可以了;
详细解析见代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#include<iostream>
#define MAXN 1000005
#define INF 1000000000
using namespace std;
struct edge
{
int u,next,cost;
};
edge edge1[MAXN],edge2[MAXN];//两种边一种是正向一种是反向;
int head1[MAXN],head2[MAXN],dis[MAXN],judge[MAXN];//指针以及最小距离和记录是否放入过队列;
int n,m;
queue<int> Q;
void SPFAGO()//SPFA算法,这个是记录去;以下是最基础的SPFA就不再多说
{
fill(dis,dis+n+1,INF);
memset(judge,0,sizeof(judge));
dis[1]=0;
judge[1]=1;
Q.push(1);
while(!Q.empty())
{
int temp=Q.front();
Q.pop();judge[temp]=0;
for(int i=head1[temp];i;i=edge1[i].next)
{
if(dis[edge1[i].u]>dis[temp]+edge1[i].cost)
{
dis[edge1[i].u]=dis[temp]+edge1[i].cost;
if(judge[edge1[i].u]==0)
{
Q.push(edge1[i].u);
judge[edge1[i].u]=1;
}
}
}
}
return ;
}
void SPFABACK()//回;
{
fill(dis,dis+n+1,INF);
memset(judge,0,sizeof(judge));
dis[1]=0;
judge[1]=1;
Q.push(1);
while(!Q.empty())
{
int temp=Q.front();
Q.pop();judge[temp]=0;
for(int i=head2[temp];i;i=edge2[i].next)
{
if(dis[edge2[i].u]>dis[temp]+edge2[i].cost)
{
dis[edge2[i].u]=dis[temp]+edge2[i].cost;
if(judge[edge2[i].u]==0)
{
Q.push(edge2[i].u);
judge[edge2[i].u]=1;
}
}
}
}
return;
}
int main()
{
int t;
int from,to,value;
__int64 ans;//这个要用64位的,要不会WA;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
memset(head1,0,sizeof(head1));//HEAD数组的初始化很重要;
memset(head2,0,sizeof(head2));
ans=0;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&from,&to,&value);
edge1[i].u=to;//edge1是正向的图;
edge1[i].cost=value;
edge1[i].next=head1[from];
head1[from]=i;
edge2[i].u=from;//edge2是反向的图;
edge2[i].cost=value;
edge2[i].next=head2[to];
head2[to]=i;
}
SPFAGO();
for(int i=1;i<=n;i++)
ans+=dis[i];
SPFABACK();
for(int i=1;i<=n;i++)
ans+=dis[i];
cout<<ans<<endl;
}
return 0;
}