A. Make A Equal to B
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given two arrays aa and bb of nn elements, each element is either 00 or 11.
You can make operations of 22 kinds.
- Pick an index ii and change aiai to 1−ai1−ai.
- Rearrange the array aa however you want.
Find the minimum number of operations required to make aa equal to bb.
Input
Each test contains multiple test cases. The first line contains a single integer tt (1≤t≤4001≤t≤400) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the length of the arrays aa and bb.
The second line of each test case contains nn space-separated integers a1,a2,…,ana1,a2,…,an (aiai is 00 or 11), representing the array aa.
The third line of each test case contains nn space-separated integers b1,b2,…,bnb1,b2,…,bn (bibi is 00 or 11), representing the array bb.
Output
For each test case, print the minimum number of operations required to make aa equal to bb.
Example
input
Copy
5
3
1 0 1
0 0 1
4
1 1 0 0
0 1 1 1
2
1 1
1 1
4
1 0 0 1
0 1 1 0
1
0
1
output
Copy
1 2 0 1 1
Note
In the first case, we need only one operation: change a1a1 to 1−ai1−ai. Now a=[0,0]a=[0,0] which is equal to bb.
In the second case, the optimal way is to rearrange aa to get the array [0,1,11[0,1,11. Now a=[0,0,1]a=[0,0,1] which is equal to bb.
In the second case, one of optimal ways would be to first change a3a3 to 1−a31−a3, then rearrange aa.
In the third case, no operation is needed.
In the fourth case, the optimal way is to rearrange aa to get the array [0,1,1,0][0,1,1,0].
题目的大致意思是给你两个01串a,b,通过两种操作让a等于b
两种操作:
1.从a中选择任意一位,把0变成1或者把1变成0
2.对a进行重新排序(以任意顺序)
问让a等于b的最小操作次数是多少
思路;
变换方式无非就以下几种:
1.只把0变成1,把1变成0
2.在一的基础上变换位置
3.只变换位置
我们可以对两种方式分别计算一遍所需的步数,最后取min输出
完整代码如下:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
while(n--)
{
int m;
cin >> m;
vector<int>a,b;
for(int i = 0; i < m; i++)
{
int t;
cin >> t;
a.push_back(t);
}
for(int i = 0; i < m; i++)
{
int t;
cin >> t;
b.push_back(t);
}
int p = 1;
for(int i = 0; i < m; i++)
{
if(a[i] != b[i])
{
p = 0;
break;
}
}
if(p)//如果a,b对应相等,直接输出0,continue后面的步骤
{
cout << 0 << '\n';
continue;
}
int x = 0;
int ans = 1;
for(int i = 0; i < m; i++)//只进行变换数字的操作,不进行排序
{
if(a[i] != b[i])
{
x++;
}
}
//排序后再进行a,b对应位置的比较,把不一样的换掉
sort(a.begin(),a.end());
sort(b.begin(),b.end());
for(int i = 0; i < m; i++)
{
if(a[i] != b[i])
{
ans ++;
}
}
ans = min(ans,x);
cout << ans << '\n';
}
return 0;
}