Codeforces Round #636 (Div. 3) 比赛人数12253
[codeforces 1343E] Weights Distributing SPFA+中转的路径
总目录详见https://blog.csdn.net/mrcrack/article/details/103564004
在线测评地址https://codeforces.com/contest/1343/problem/E
Problem | Lang | Verdict | Time | Memory |
---|---|---|---|---|
E - Weights Distributing | GNU C++17 | Accepted | 187 ms | 17200 KB |
思路同https://www.cnblogs.com/qieqiemin/p/12753547.html
所有的路径情况可以被分类成两种:
1️⃣:
(a−>b),(b−>c)两个径直的路径,有且仅有一个连接点b,样例二就是这一类。
2️⃣:
存在一个非b的节点x,路径为:(a−>x),(x−>b),(b−>x),(x−>c),样例一就属于这一类。
仔细思考的话可以发现,两种情况可以都归纳为情况2️⃣,
因为a,b,c都是确定的,那么我们不枚举节点x,
在枚举之前,我们通过3次bfs算法分别求出以a,b,c为源点的到达地i
个节点的最短距离(需要经历多少个边)。
因为(b−>x)这个路径需要被走两次,那么我们肯定优先把边权小的边放在路径(b−>x)上。
只需要将数组p排序后做个sum和即可O(m∗log2(m)+n)的时间复杂度内解决该问题。
样例解释如下
(2,3,4) 2->1->3->1->4
(a->i)+2*(b->i)+(c->i)
i=1 (a->1)+2*(b->1)+(c->1)
(1,5,7) 1->5->7 a->b->c
(a->i)+2(b->i)+(c->i)
i=b (a->b)+2*(b->b)+(c->b)
AC代码如下
#include <cstdio>
#include <algorithm>
#define LL long long
#define maxn 200010
using namespace std;
LL sum[maxn];
int head[maxn],tot,da[maxn],db[maxn],dc[maxn],vis[maxn],q[maxn*10],p[maxn];
int n,m;
struct node{
int to,next;
}e[maxn<<1];
void add_edge(int u,int v){
tot++,e[tot].to=v,e[tot].next=head[u],head[u]=tot;
}
void SPFA(int s,int *d){
int h,t,b,u,v,i;
for(i=1;i<=n;i++)vis[i]=0;
for(i=1;i<=n;i++)d[i]=maxn;
h=t=1,q[t]=s,t++,vis[s]=1,d[s]=0;
while(h<t){
u=q[h];
for(b=head[u];b;b=e[b].next){
v=e[b].to;
if(d[v]>d[u]+1){
d[v]=d[u]+1;
if(!vis[v])vis[v]=1,q[t]=v,t++;
}
}
vis[u]=0,h++;
}
}
int main(){
int t,a,b,c,u,v,i;
LL ans;
scanf("%d",&t);
while(t--){
scanf("%d%d%d%d%d",&n,&m,&a,&b,&c);
for(i=1;i<=m;i++)scanf("%d",&p[i]);
sort(p+1,p+1+m);//自小到大排序
for(i=1;i<=m;i++)sum[i]=sum[i-1]+p[i];//前缀和
tot=0;
for(i=1;i<=n;i++)head[i]=0;//此行不能漏
for(i=1;i<=m;i++){
scanf("%d%d",&u,&v);
add_edge(u,v),add_edge(v,u);
}
SPFA(a,da);
SPFA(b,db);
SPFA(c,dc);
ans=1e15;
for(i=1;i<=n;i++){
if(da[i]+db[i]+dc[i]>m)continue;//防止sum[]数组访问越界
ans=min(ans,2*sum[db[i]]+sum[da[i]+db[i]+dc[i]]-sum[db[i]]);
}
printf("%lld\n",ans);
}
return 0;
}