题目链接
Kruskal 思想的扩展,一开始想到了贪心取各行各列中的最小边权,但是没有把握好环的判断问题,只敲了个裸的 Kruskal 水了水,后面参考了洛谷第一篇的题解,其实就是简单地记录一下已经取的行/列的数目就行啦…
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=310*310;
const int maxm=310*310*2;
int n,m,tot,idx=0,f[maxn],a[maxn/2],b[maxn/2];
struct Edge{int from,to,dis;Edge(){}Edge(int ff,int tt,int dd):from(ff),to(tt),dis(dd){}bool operator<(const Edge &e)const{return dis<e.dis;}
}edge[maxm];int father(int x){while(x!=f[x]){f[x]=f[f[x]];x=f[x];}return x;
}void unionfather(int x,int y){f[father(y)]=father(x);
}void Kruskal(){for(int i=1;i<=tot;i++)f[i]=i;sort(edge,edge+idx);ll ans=0,cnt=0;for(int i=0;i<idx;i++){if(cnt==tot-1)break;if(father(edge[i].from)!=father(edge[i].to)){unionfather(edge[i].from,edge[i].to);ans=(ll)ans+(ll)edge[i].dis;cnt++;}}printf("%lld\n",ans);
} int main()
{scanf("%d%d",&n,&m);tot=n*m; for(int i=1;i<=n;i++){scanf("%d",&a[i]);int from,to=(i-1)*m+1;for(int j=1;j<m;j++){ from=to;to=from+1;edge[idx++]=Edge(from,to,a[i]);}} for(int i=1;i<=m;i++){scanf("%d",&b[i]);int from,to=i;for(int j=1;j<n;j++){from=to;to=from+m;if(to>tot) break;edge[idx++]=Edge(from,to,b[i]);}} Kruskal();return 0;
}
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=3e5+10;
int n,m,a[maxn],b[maxn];
ll ans;
int main()
{scanf("%d%d",&n,&m);for(int i=1;i<=n;i++)scanf("%d",&a[i]); for(int j=1;j<=m;j++)scanf("%d",&b[j]); sort(a+1,a+1+n);sort(b+1,b+1+m); ans=(ll)a[1]*(m-1)+(ll)b[1]*(n-1);int i=2,j=2,row=1,col=1;while(i<=n&&j<=m){if(a[i]<=b[j]){ans+=(ll)a[i++]*(m-col);row++;}else{ans+=(ll)b[j++]*(n-row);col++;}}printf("%lld",ans);return 0;
}