Educational Codeforces Round 6-D. Professor GukiZ and Two Arrays
程序员文章站
2022-03-04 21:10:40
...
地址:http://codeforces.com/contest/620/problem/D
思路:对于交换0可以直接判断,1次可以将b[]保留下标并按值由小到大排序,在二分查找,即a[],b[]的总和差值ss,对b[]查找a[i]-ss/2的值即可,而对于2次交换,可以将b[]的所有组合情况保存在二分即可
Code :
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
struct node{
int a;
int b;
LL w;
bool operator<(const node &p)const{
return w<p.w;
}
};
const LL INF=1e15;
const int MAX_N=2005;
const int MAX_S=4000005;
int n,m;
node a[MAX_N],b[MAX_N];
node d[MAX_S];
int main()
{
ios::sync_with_stdio(false);
cin>>n;
int t=-1;
LL sum1=0,sum2=0;
for(int i=0;i<n;++i)
{
cin>>a[i].w;
a[i].a=i+1; sum1+=a[i].w;
}
cin>>m;
for(int i=0;i<m;++i)
{
cin>>b[i].w;
b[i].b=i+1; sum2+=b[i].w;
}
sort(a,a+n); sort(b,b+m);
int aa,bb,a1,a2,b1,b2;
LL ss=sum1-sum2,s1=INF,s2=INF,sx,k;
if(sum1==sum2) t=0;
if(t==-1){
for(int i=0;i<n;++i)
{
k=lower_bound(b,b+m,node{0,0,a[i].w-ss/2})-b;
sx=abs(a[i].w*2-b[k].w*2-ss);
if(k!=m&&s1>sx){
s1=sx;
aa=a[i].a; bb=b[k].b;
}
sx=abs(a[i].w*2-b[k-1].w*2-ss);
if(k&&s1>sx){
s1=sx;
aa=a[i].a; bb=b[k-1].b;
}
}
int mm=0;
for(int i=0;i<m;++i)
for(int j=i+1;j<m;++j)
d[mm++]=node{b[i].b,b[j].b,b[i].w+b[j].w};
sort(d,d+mm);
LL p;
for(int i=0;i<n;++i)
{
for(int j=i+1;j<n;++j)
{
p=a[i].w+a[j].w;
k=lower_bound(d,d+mm,node{0,0,p-ss/2})-d;
sx=abs(p*2-d[k].w*2-ss);
if(k!=mm&&s2>sx){
s2=sx;
a1=a[i].a; a2=a[j].a; b1=d[k].a; b2=d[k].b;
}
sx=abs(p*2-d[k-1].w*2-ss);
if(k&&s2>sx){
s2=sx;
a1=a[i].a; a2=a[j].a; b1=d[k-1].a; b2=d[k-1].b;
}
}
}
if(s1<=s2) t=1;
else t=2;
}
if(s1==INF&&s1==s2) s1=0;
cout<<min(s1,s2)<<endl;
cout<<t<<endl;
if(t==1) cout<<aa<<" "<<bb<<endl;
else if(t==2){
cout<<a1<<" "<<b1<<endl;
cout<<a2<<" "<<b2<<endl;
}
return 0;
}
上一篇: JAVA人机交互Scanner的使用
下一篇: 数据结构和算法:03.冒泡、选择排序
推荐阅读
-
C. Two Arrays(组合数学/动态规划) Educational Codeforces Round 80 (Rated for Div. 2)
-
Educational Codeforces Round 80 (CF - 1288C - Two Arrays)
-
codeforces Educational Codeforces Round 80 (Rated for Div. 2) C - Two Arrays(简单dp)
-
【Educational Codeforces Round 80(div2)】C-Two Arrays dp/组合数
-
Educational Codeforces Round 80 (Rated for Div. 2) C - Two Arrays(DP)
-
Educational Codeforces Round 6-D. Professor GukiZ and Two Arrays