链式前向星存图
这类问题最好还是long long ,感觉这种类型的不是ll好像A不了似的,怕了怕了。还有一个最短路的最优化。我也不知道咋弄的,反正知道是这个意思。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <stack>
#include <queue>
using namespace std;
typedef long long ll;
const int shuzu = 1e6+2;
#define MAXN 0x3f3f3fff
int n,k,cnt;
int mapp[shuzu][3];
int head[shuzu];
bool vis[shuzu];
int dis[shuzu];
struct node
{
int to,next,w;
}edge[shuzu];
void add(int u,int v,int w)
{
edge[cnt] = {v,head[u],w};
head[u] = cnt++;
}
void init()
{
cnt = 0;
memset(head,-1,sizeof(head));
memset(vis,false,sizeof(vis));
for(int i=0;i<=n;i++)
dis[i] = MAXN;
}
ll spfa()
{
queue<int > Q;
int to,w;
Q.push(1);
vis[1] = true;
dis[1] = 0;
while(!Q.empty())
{
int t=Q.front();
Q.pop();
vis[t] = false;
for(int i=head[t];i!=-1;i=edge[i].next)
{
to = edge[i].to;
w = edge[i].w;
if(dis[to]>dis[t]+w)
{
dis[to] = dis[t] + w;
if(!vis[to])
{
Q.push(to);
vis[to] = true;
}
}
}
}
ll ans = 0;
for(int i=1;i<=n;i++)
{
ans += dis[i];
}
return ans;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&k);
init();
for(int i=1;i<=k;i++)
{
scanf("%d%d%d",&mapp[i][0],&mapp[i][1],&mapp[i][2]);
add(mapp[i][0],mapp[i][1],mapp[i][2]);
}
ll ans1 = spfa();
init();
for(int i=1;i<=k;i++)
{
add(mapp[i][1],mapp[i][0],mapp[i][2]);
}
ll ans2 = spfa();
printf("%lld\n",ans1+ans2);
}
return 0;
}