题目:http://codeforces.com/contest/620/problem/D
题意:给你两个数组,a数组和b数组
你有操作–将a数组数组中的一个元素与b数组中的一个元素交换
这种操作只能出现k次(0<=k<=2),使得abs(∑a-∑b)最小
输出方案
思路:
k = 0……
k = 1,(∑a-a[i]+b[j])-(∑b+a[i]-b[j]) = ∑a-∑b+2(b[j]-a[i])
k = 2,将a任意两项合成一项,b两项任意两项合成一项,然后参考”k=1”,二分查找
代码参考卿学姐
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2005;
int a[N],b[N];
pair<int,int> p1;
pair<int,int> q1,q2;
pair<ll, pair<int,int> > p[N*N];
int main()
{
int n,m;
ll d0 = 0;//不交换
scanf("%d",&n);
for(int i = 1;i <= n;i++)
scanf("%d",&a[i]),d0 += a[i];
scanf("%d",&m);
for(int j = 1;j <= m;j++)
scanf("%d",&b[j]),d0 -= b[j];
ll d1 = 1e18;//交换一次
for(int i = 1;i <= n;i++)
for(int j = 1;j <= m;j++)
{
if(d1 > abs(d0-2*a[i]+2*b[j]))
{
d1 = abs(d0-2*a[i]+2*b[j]);
p1 = make_pair(i,j);
}
}
int cnt = 0;
for(int i = 1;i <= m;i++)
for(int j = i+1;j <= m;j++)
p[++cnt] = make_pair(2ll*b[i]+2ll*b[j], make_pair(i,j));
sort(p+1,p+cnt+1);
ll d2 = 1e18;//交换两次
for(int i = 1;i <= n;i++)
{
for(int j = i+1;j <= n;j++)
{
ll tmp = 2ll*a[i]+2ll*a[j] - d0;
int pos = lower_bound(p+1,p+cnt+1,make_pair(tmp,make_pair(0,0)))-p;
for(int k = max(1,pos-2);k <= min(cnt,pos+2);k++)
{
if(abs(p[k].first-tmp) < d2)
{
d2 = abs(p[k].first-tmp);
q1 = make_pair(i,p[k].second.first);
q2 = make_pair(j,p[k].second.second);
}
}
}
}
//cout<<d0<<" "<<d1<<" "<<d2<<endl;
d0 = abs(d0);
ll minn = min(d0,min(d1,d2));
printf("%lld\n",minn);
if(minn == d0)
printf("0\n");
else if(minn == d1)
printf("1\n%d %d\n",p1.first,p1.second);
else
printf("2\n%d %d\n%d %d\n",q1.first,q1.second,q2.first,q2.second);
return 0;
}