B. Ternary Sequence

传送门
B. Ternary Sequence
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given two sequences a1,a2,…,an and b1,b2,…,bn. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x1, y1, z1 respectively, and the number of elements 0, 1, 2 in the sequence b is x2, y2, z2respectively.
You can rearrange the elements in both sequences a and b however you like. After that, let’s define a sequence c as follows:

You’d like to make ∑ni=1ci(the sum of all elements of the sequence c) as large as possible. What is the maximum possible sum?

Input
The first line contains one integer t(1≤t≤104) — the number of test cases.
Each test case consists of two lines. The first line of each test case contains three integers x1, y1, z1 (0≤x1,y1,z1≤108) — the number of 0-s, 1-s and 2-s in the sequence a The second line of each test case also contains three integers x2, y2, z2 (0≤x2,y2,z2≤108;x1+y1+z1=x2+y2+z2>0) — the number of 0-s, 1-s and 2-s in the sequence b

Output
For each test case, print the maximum possible sum of the sequence c

Example
Input

3
2 3 2
3 3 1
4 0 1
2 3 0
0 0 1
0 0 1

Output

4
2
0

Note
In the first sample, one of the optimal solutions is:
a={2,0,1,1,0,2,1}
b={1,0,1,0,2,1,0}
c={2,0,0,0,0,2,0}
In the second sample, one of the optimal solutions is:
a={0,2,0,0,0}
b={1,1,0,1,0}
c={0,2,0,0,0}
In the third sample, the only possible solution is:
a={2}
b={2}
c={0}

题意:已知两个序列a1 a2…an和b1 b2…bn。两个序列的每个元素要么是0,要么是1,要么是2。a数列中元素0,1,2的个数分别为x1, y1, z1, b数列中元素0,1,2的个数分别为x2, y2, z2。你可以重新排列两个序列a与b中的元素,后定义一个c序列,a与b序列对应的情况可以推出相应的c序列,1.a>b,c=ab; 2.a=b,c=0; 3.a<b,c=-ab;后对c序列中数字求和,求出和的最大值并输出。

思路:我们可以找到ci值为3(−2,0,2)的种类。 并且只有当ai 为1且bi为2时ci才为−2,只有当ai为2且bi为1时ci才为2。否则ci为0。所以我们必须使(ai,bi)对(1,2) 尽可能少,并尽可能多地配对(2,1)。 为此,首先我们可以使(1,0)对,(0,2)对和(2,1)对尽可能多。 之后,将剩余值配对不会影响ci的总和。

AC代码

#include<bits/stdc++.h>
using namespace std;
int main(){
	int t;cin>>t;
	while(t--){
		int m,sum=0,x0,x1,x2,y0,y1,y2;
		cin>>x0>>x1>>x2>>y0>>y1>>y2;
		m=min(x0,y2);
		x0-=m;
		y2-=m;
		m=min(x1,y0);
		x1-=m;
		y0-=m;
		m=min(x2,y1);
		x2-=m;
		y1-=m;
		sum+=2*m;
		sum-=2*min(x1,y2);
		cout<<sum<<endl;
	}return 0;
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

稚皓君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值