这题数据量大的惊人,不过难度不大,正向建图后再反向建图,跑2遍spfa算法就好了,超内存请用c++提交
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#define inf 1<<30
#define maxn 1000010
using namespace std;
struct stu
{
int next,l;
};
vector<stu>mapp1[maxn];
vector<stu>mapp2[maxn];
int n;
int d[maxn];
void init()
{
for(int i=1;i<=n;i++) mapp1[i].clear(),mapp2[i].clear();
}
void input()
{
int m;
cin>>n>>m;
for(int i=0;i<m;i++)
{
int x,y,z;
cin>>x>>y>>z;
stu root;
root.next=y;
root.l=z;
mapp1[x].push_back(root);
root.next=x;
mapp2[y].push_back(root);
}
}
void bfs(int flag)
{
fill(d,d+n+1,inf);
d[1]=0;
queue<int>q;
q.push(1);
int x,y;
while(q.size())
{
x=q.front();
q.pop();
if(flag==1)
{
for(int i=0;i<mapp1[x].size();i++)
{
stu root=mapp1[x][i];
y=root.next;
if(d[y]==inf||d[y]>d[x]+root.l)
{
d[y]=d[x]+root.l;
q.push(y);
}
}
}
else
{
for(int i=0;i<mapp2[x].size();i++)
{
stu root=mapp2[x][i];
y=root.next;
if(d[y]==inf||d[y]>d[x]+root.l)
{
d[y]=d[x]+root.l;
q.push(y);
}
}
}
}
}
void solve()
{
int sum=0;
bfs(1);
for(int i=1;i<=n;i++) sum+=d[i];
// cout<<sum<<endl;
bfs(2);
for(int i=1;i<=n;i++) sum+=d[i];
cout<<sum<<endl;
}
int main()
{
cin.sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
init();
input();
solve();
}
return 0;
}