本文主要是介绍Codeforces1401 B. Ternary Sequence,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
You are given two sequences 𝑎1,𝑎2,…,𝑎𝑛 and 𝑏1,𝑏2,…,𝑏𝑛. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence 𝑎 is 𝑥1, 𝑦1, 𝑧1 respectively, and the number of elements 0, 1, 2 in the sequence 𝑏 is 𝑥2, 𝑦2, 𝑧2 respectively.
You can rearrange the elements in both sequences 𝑎 and 𝑏 however you like. After that, let’s define a sequence 𝑐 as follows:
𝑐𝑖=⎧⎩⎨⎪⎪𝑎𝑖𝑏𝑖0−𝑎𝑖𝑏𝑖if 𝑎𝑖>𝑏𝑖if 𝑎𝑖=𝑏𝑖if 𝑎𝑖<𝑏𝑖
You’d like to make ∑𝑛𝑖=1𝑐𝑖 (the sum of all elements of the sequence 𝑐) as large as possible. What is the maximum possible sum?
Input
The first line contains one integer 𝑡 (1≤𝑡≤104) — the number of test cases.
Each test case consists of two lines. The first line of each test case contains three integers 𝑥1, 𝑦1, 𝑧1 (0≤𝑥1,𝑦1,𝑧1≤108) — the number of 0-s, 1-s and 2-s in the sequence 𝑎.
The second line of each test case also contains three integers 𝑥2, 𝑦2, 𝑧2 (0≤𝑥2,𝑦2,𝑧2≤108; 𝑥1+𝑦1+𝑧1=𝑥2+𝑦2+𝑧2>0) — the number of 0-s, 1-s and 2-s in the sequence 𝑏.
Output
For each test case, print the maximum possible sum of the sequence 𝑐.
Example
inputCopy
3
2 3 2
3 3 1
4 0 1
2 3 0
0 0 1
0 0 1
outputCopy
4
2
0
Note
In the first sample, one of the optimal solutions is:
𝑎={2,0,1,1,0,2,1}
𝑏={1,0,1,0,2,1,0}
𝑐={2,0,0,0,0,2,0}
In the second sample, one of the optimal solutions is:
𝑎={0,2,0,0,0}
𝑏={1,1,0,1,0}
𝑐={0,2,0,0,0}
In the third sample, the only possible solution is:
𝑎={2}
𝑏={2}
𝑐={0}
思路:
贪心的想,就是a数组中的2,肯定是和b数组中的1、2、0依次匹配。
a数组中的1,0肯定是和b数组中的1、0、2。
原因是对2来说只有放1才有贡献,否则剩下不如放2,再其次是0。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>using namespace std;typedef long long ll;const int maxn = 1e5 + 7;int mp1[10] = {2,1,0};
int mp2[10] = {1,0,2};int main() {int T;scanf("%d",&T);while(T--) {int a[10],b[10];scanf("%d%d%d",&a[2],&a[1],&a[0]); //2,1,0scanf("%d%d%d",&b[1],&b[0],&b[2]); //1,0,2int ans = 0;for(int i = 0;i <= 2;i++) { //1 2 0if(i == 0) {swap(b[1],b[2]);mp2[1] = 2;mp2[2] = 0;}for(int j = 0;j <= 2;j++) {int num = min(a[i],b[j]);a[i] -= num;b[j] -= num;if(mp1[i] > mp2[j]) {ans += num * mp1[i] * mp2[j];} else if(mp1[i] < mp2[j]) {ans += -num * mp1[i] * mp2[j];} else {ans += 0;}}if(i == 0) {swap(b[1],b[2]);mp2[1] = 0;mp2[2] = 2;}}printf("%d\n",ans);}return 0;
}
这篇关于Codeforces1401 B. Ternary Sequence的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!