codeforces#1343E. Weights Distributing(bfs)

E. Weights Distributing

Title

Given an undirected graph with the number of points \ (n \) and the number of edges \ (m \) , seek to assign \ (m \) weights to these edges such that \ (a \) to \ (b \) to The minimum cost of the \ (c \) path

analysis

In the optimal solution, the route must be \ (a \) -> \ (x \) -> \ (b \) -> \ (x \) -> \ (c \) , \ (x \) can be Any point, and \ (x \) -> \ (b \) and \ (b \) -> \ (x \) must pass through the same edge

AC code

#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for (int i=(a);i<=(b);i++)
#define per(i,a,b) for (int i=(b);i>=(a);i--)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define SZ(x) ((int)(x).size())

typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> PII;

const ll mod=998244353 ;
const int maxn=2e5+7;
ll pre[maxn];
int num[maxn],dis1[maxn],dis2[maxn],dis3[maxn],vis[maxn];
VI ve[maxn];
int T,n,m,a,b,c;

void bfs(int x,int dis[]){
	rep(i,1,n)vis[i]=0;
	dis[x]=0;
	vis[x]=1;
	queue<int>que;
	que.push(x);
	while(SZ(que)){
		int now=que.front();
		que.pop();
		for(auto i:ve[now]){
			if(vis[i]==0){
				vis[i]=1;
				dis[i]=dis[now]+1;
				que.push(i);
			}
		}
	}
	// rep(i,1,n)printf("%d ",dis[i]);
	// cout<<endl;
}
int main() {
	scanf("%d",&T);
	while(T--){
		scanf("%d %d %d %d %d",&n,&m,&a,&b,&c);
		rep(i,1,m)scanf("%d",&num[i]);
		rep(i,1,m){
			int a,b;
			scanf("%d %d",&a,&b);
			ve[a].pb(b);
			ve[b].pb(a);
		}
		sort(num+1,num+1+m);
		rep(i,1,m)
			pre[i]=pre[i-1]+num[i];
		// cout<<endl;
		bfs(a,dis1);
		bfs(b,dis2);
		bfs(c,dis3);
		ll ans=1e18;
		rep(x,1,n){
			if(dis1[x]+dis2[x]+dis3[x]>m)continue;
			ans=min(ans,pre[dis1[x]+dis2[x]+dis3[x]]+pre[dis2[x]]);
		}
		printf("%lld\n",ans);
		rep(i,1,n)ve[i].clear();
	}
    return 0;
}

Guess you like

Origin www.cnblogs.com/carcar/p/12751018.html