GALACTIK - Editorial

WA plz corret me

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

#define pi(x) cout<<x;
#define ps(x) cout<<x<<" β€œ;
#define pnl(x) cout<<x<<”\n";
#define for0(n) for(i=0;i<n;i++)
#define for1(n) for(i=1;i<=n;i++)
#define m(x) memset(x,0,sizeof x);
#define nl cout<<"\n";
#define mp make_pair
#define pb push_back
#define fr first
#define se second
#define Inf 1e16
vectora[100009];
vectorb(100009);
ll dp[100009];
ll maxx=INT_MAX;

void dfs(ll v){
if(dp[v]){
return;
}
dp[v]=1;
if(b[v]>=0){
maxx=min(maxx,b[v]);
}
for(ll i=0;i<a[v].size();i++){
dfs(a[v][i]);
}

}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll test,i,j,xy,flag=0,n,u,count,d,o1=0,o2=0,s,e,l,r,x,y,m,z,max1,x1,y1,k,x2,y2,z1,sum,f,min1;

cin>>n>>m;
for(i=0;i<m;i++){
cin>>x>>y;
a[x].push_back(y);
a[y].push_back(x);
}
for(i=1;i<=n;i++){
cin>>b[i];
}
d=INT_MAX;
memset(dp,0,sizeof dp);
vectorans;
min1=INT_MAX;
for(i=1;i<=n;i++){
maxx=INT_MAX;
if(dp[i]==0){
dfs(i);
if(maxx==d){
cout<<"-1";
return 0;
}
ans.push_back(maxx);
min1=min(maxx,min1);
}
}
sum=0;
sort(ans.begin(),ans.end());
for(i=1;i<ans.size();i++){
sum+=ans[i]+ans[0];
}

cout<<sum<<"\n";

return 0;
}

alexrider | CodeChef User Profile for Sreemanti Dey | CodeChef can you please help? I implemented exactly the same idea, but still WA :((( handled all boundary cases, like n==1. I checked on whatever tcs that came to my mind still WA

If you see the expression in the explanation above it is
cost[x] * (K-1) + sum - cost[x]

which can also be written as

cost[x] * (K - 2) + sum.

How did we get this?
Let’s say there are 4 disjoint sets (or components) and min cost of each of the component is a, b, c, d and a < b,c,d.
This means sum = a + b + c + d and cost[x] = a.

There will be K-1 paths from vertex with cost a => cost of each path = a + cost[v2], where v2 is the other vertex in the path.

=> cost = a * (K-1) + b + c + d = a * (K-1) + sum - a = a * (K - 2) + sum = cost[x] * (K -2 ) + sum

Took me a while to figure out as well. Hope it helps : )

thank you @samkit for the approach as
dfs approach is much simpler