Codeforces Round #618(Div. 2) (全题解)
A. Non-zero
思路:要满足乘积不为0,只需要所有的数均不为0即可;要满足和不为0,在任意一个数加一即可。因此只需要记录0的数量cnt
和所有数的和sum
,让所有的0加一之后,看和是否为0,如果和为0,再找一个不是-1的数加一即可。
AC代码:
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
#define maxn 200005
int t, sum, cnt, n;// cnt 记录0的个数,sum记录所有数的和
int main()
{
cin >> t;
while (t--)
{
cin >> n;
cnt = 0; sum = 0;//初始化
while (n--)
{
int tmp;
cin >> tmp;
if (tmp == 0) cnt++;
sum += tmp;
}
cout << cnt + (sum + cnt == 0) << endl; // 对所有0加一之后如果和为0还要再进行一次操作
}
return 0;
}
B. Assigning to Classes
思路:可以验证,将数列排序后对半分,两个中位数必不可能落在同一边。所以,取最中间的两个数作为两个中位数是最优的选择。
AC代码:
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
#define maxn 200005
int n, t;
int a[maxn];
int main()
{
cin >> t;
while (t--)
{
cin >> n;
for (int i = 0; i < (n << 1); i++)
{
cin >> a[i];
}
sort(a, a + (n << 1));
cout << a[n] - a[n - 1] << endl;
}
return 0;
}
C. Anu Has a Function
思路:先分析 f ( x , y ) = ( x ∣ y ) − y f(x,y)=(x|y)-y f(x,y)=(x∣y)−y,对于|运算,其与+运算不同的地方在于 1 ∣ 1 = 1 1|1=1 1∣1=1,而 1 + 1 = ( 10 ) 2 1+1=(10)_2 1+1=(10)2,所以 f ( x , y ) = ( x + y ) −