source : poj 1511
题意很简单,让我用markdown画出来就可以了
有道云笔记语法和这里不一样,懒得改了。。。。
graph LR
1 --> 2
2 --> 1
1 --> 3
3 --> 4
2 --> 4
4 --> 50
好吧图很丑,不过勉强能看,每条单向边都有一个权,表示车票,现在我们要从1出发,把n个人送到n个顶点,之后送出去的n个人要回来1,问着一去一回需要多少车票钱,第二组样例为(50+60+70)+(5+15+10)=210
解决方法也很简单,题目所给的正向边跑一次最短路,求和得到sum1,根据题目的正向边,建立反向边组成的图,再从1出发跑一次最短路即可。
这个题给的数据很卡时间,所以这里我们使用堆优化的dijkstra算法
#include <vector>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1000005;
const int maxm = 1000005;
const int INF = 0x3f3f3f3f;
int n,m;
struct Edge
{
int from,to,w,next;
};
struct Pair
{
int v,distance;
bool operator < (const Pair &t) const
{
return distance > t.distance; //需要最小的,所以我们从大到小排序
}
};
int pre1[maxn];
int pre2[maxn];
Edge e1[maxm];
Edge e2[maxm];
priority_queue<Pair> pq;
bool vis[maxn];
int dis1[maxn];
int dis2[maxn];
int main()
{
#ifdef LOCAL_DEBUG
freopen("input.txt","r",stdin);
#endif // LOCAL_DEBUG
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d" ,&n,&m);
memset(pre1,-1,sizeof(pre1));
memset(pre2,-1,sizeof(pre2));
int from,to,w;
for(int i=1; i<=m; i++)
{
scanf("%d%d%d" ,&from,&to,&w);
e1[i].from=from;
e1[i].to=to;
e1[i].w=w;
e1[i].next=pre1[from];
pre1[from]=i;
swap(from,to);
e2[i].from=from;
e2[i].to=to;
e2[i].w=w;
e2[i].next=pre2[from];
pre2[from]=i;
}
while(!pq.empty()) pq.pop();
memset(dis1,INF,sizeof(dis1));
memset(vis,0,sizeof(vis));
dis1[1]=0;
pq.push( (Pair){1,0} );
while(!pq.empty())
{
Pair t = pq.top();
pq.pop();
//如果t.distance == dis1[t.v]说明是t更新的dis数组,现在不相等,说明已经有与t编号相同,距离更小的已经过邻接边了.
if(t.distance != dis1[t.v]) continue;
vis[t.v]=true; //从所有可行状态中出队代表已经获得永久标号
for(int i=pre1[t.v]; i!=-1; i=e1[i].next)
{
if(vis[e1[i].to]) continue;
if(dis1[e1[i].to] > dis1[t.v] + e1[i].w)
{
dis1[e1[i].to] = dis1[t.v] + e1[i].w;
pq.push( (Pair){e1[i].to,dis1[e1[i].to]} );
}
}
}
while(!pq.empty()) pq.pop();
memset(dis2,INF,sizeof(dis2));
memset(vis,0,sizeof(vis));
dis2[1]=0;
pq.push( (Pair){1,0} );
while(!pq.empty())
{
Pair t = pq.top();
pq.pop();
if(t.distance != dis2[t.v]) continue;
vis[t.v]=true;
for(int i=pre2[t.v]; i!=-1; i=e2[i].next)
{
if(vis[e2[i].to]) continue;
if(dis2[e2[i].to] > dis2[t.v] + e2[i].w)
{
dis2[e2[i].to] = dis2[t.v] + e2[i].w;
pq.push( (Pair){ e2[i].to,dis2[e2[i].to]} );
}
}
}
long long ans=0;
for(int i=1;i<=n;i++)
{
ans+=(long long)dis1[i]; ans+=(long long)dis2[i];
}
printf("%lld\n",ans);
}
return 0;
}