D. Zero Quantity Maximization
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given two arrays aa and bb , each contains nn integers.
You want to create a new array cc as follows: choose some real (i.e. not necessarily integer) number dd , and then for every i∈[1,n]i∈[1,n] let ci:=d⋅ai+bici:=d⋅ai+bi .
Your goal is to maximize the number of zeroes in array cc . What is the largest possible answer, if you choose dd optimally?
Input
The first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105 ) — the number of elements in both arrays.
The second line contains nn integers a1a1 , a2a2 , ..., anan (−109≤ai≤109−109≤ai≤109 ).
The third line contains nn integers b1b1 , b2b2 , ..., bnbn (−109≤bi≤109−109≤bi≤109 ).
Output
Print one integer — the maximum number of zeroes in array cc, if you choose dd optimally.
题目的大概意思就是给你一串a[i], 一串b[i], 让你找到一个数d,使c[i] = a[i] * d + b[i]为0的数量最多。
由于a[i] * d + b[i] = 0,所以d = -b[i] / a[i]. 若又两组a, b具有相同的d,则它们的最简分式相同。所以本题就变成了求最大公约数。
以下是代码
#include <iostream>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <vector>
#include <stdio.h>
#include <map>
using namespace std;
#define LL long long
typedef pair<int, int> pii;
const int MAX = 2e5 + 50;
int gcd(int a, int b){
return b == 0? a : gcd(b, a % b);
}
map<pii, int> mp;
int a[MAX];
int b[MAX];
int main(int argc, char const *argv[])
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
for(int i = 0; i < n; i++){
scanf("%d", &b[i]);
}
int cnt = 0;
for(int i = 0; i < n; i++){
if(a[i] != 0){
if(a[i] < 0){// 因为是用map存,像-1,4 和1, -4这样的情况会被视为不相同,所以若a为负数,则变为正数,b变为相反数
a[i] = -a[i];
b[i] = -b[i];
}
int x = gcd(a[i], abs(b[i]));
pii p;
p.first = a[i] / x;
p.second = b[i] / x;
mp[p]++;
} else{
if(b[i] == 0){ // 注意 0, 0的情况,不管b去什么,结果都为0
cnt++;
}
}
}
int ans = 0;
for(auto x: mp){
ans = max(ans, x.second); //取最大的情况
}
printf("%d\n", ans + cnt); // 加上cnt
return 0;
}