# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
850788 | emad234 | Art Collections (BOI22_art) | C++17 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define aint(v) ((v).begin(),(v).end())
#define ll long long
#define F first
#define S second
using namespace std;
const int mod = 1e9 + 7;
const int mxN = 1e7 + 5;
int p[mxN];
struct edge{
int cost;
int x,y;
};
bool operator<(edge a, edge b){
return a.cost < b.cost;
}
int find(int x){
return (p[x] == x ? x : p[x] = find(p[x]));
}
void merge(int a,int b){
int fa = find(a),fb = find(b);
p[fa] = p[fb] = p[a] = p[b] = (rand() % 2 ? fa : fb);
}
int a[2030],b[2030];
edge v[mxN];
signed main()
{
freopen("fencedin.in", "r", stdin);
freopen("fencedin.out", "w", stdout);
int A,B,n,m;
cin >>A>>B>>n>>m;
a[n + 1] = A;
b[m + 1] = B;
for(int i = 1;i <= n;i++) cin>>a[i];
for(int i = 1;i <= m;i++) cin >>b[i];
n += 2;
m += 2;
sort(a,a + n);
sort(b,b + m);
int id = 0;
for(int i = 1;i <= 1e7;i++) p[i] = i;
for(int i = 1;i < n;i++){
int prev = (a[i - 1]);
int off = i * (m - 1) - (m - 1);
for(int j = 1;j < m;j++){
int prevm = (b[j - 1]);
if(j != m - 1){
v[id] = {a[i] - prev,j + off,j + 1 + off};
id++;
}
if(i != n - 1){
v[id] = {b[j] - prevm,j + off,j + (m - 1) + off};
id++;
}
}
}
sort(v,v + id + 1);
ll ans = 0;
for(int i = 0;i <= id;i++){
auto x = v[i];
// cout<<x.x<<' '<<x.y<<' '<<x.cost<<'\n';
if(find(x.x) != find(x.y)){
ans += x.cost;
merge(x.x,x.y);
}
}
cout<<ans;
}