题目 | Many Perfect Squares
Codeforces Round #844 (Div. 1 + Div. 2, based on VK Cup 2022 - Elimination Round)
D. Many Perfect Squares
https://codeforces.com/contest/1782/problem/D
4 seconds / 512 megabytes
standard input / standard output
Problem
You are given a set
We define the squareness of an integer
Find the maximum squareness among all integers
Perfect squares are integers of the form
Input
Each test contains multiple test cases. The first line contains the number of test cases
The first line of each test case contains a single integer
The second line contains
It is guaranteed that the sum of
Output
For each test case, print a single integer — the largest possible number of perfect squares among
Example
Input
4
5
1 2 3 4 5
5
1 6 13 22 97
1
100
5
2 5 10 17 26
Output
2
5
1
2
Note
In the first test case, for
In the second test case, for
题解
核心思路
首先,
减小 的规模
首先我们可以确定的是,答案最小为
我们继续判断答案是否
由于最多有
给定一对数如何求解
该问题的形式化表述为:取任意
三个未知数
为了简洁,令
将
若
回代
若
时间复杂度
最多
通过遍历确定答案,数量级为
综上,时间复杂度勉强写成:
用
由于正因子个数的无法直接计算,而且对于一个正因子,也不一定有解,所以这个时间复杂度没办法准确表述,实际情况应该远小于上述复杂度。
代码
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
bool is_square(int n)
{
int r = sqrt(1.0L * n);
return r * r == n;
}
void solve()
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
int ans = 1;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
int t = a[j] - a[i];
for (int p = 1; p * p <= t; p++)
{
if (t % p)
continue;
int q = t / p;
if ((q - p) % 2)
continue;
int u = (q - p) / 2, v = (q + p) / 2;
int x = u * u - a[i];
if (x < 0)
continue;
int res = 0;
for (int ii = 0; ii < n; ii++)
if (is_square(a[ii] + x))
res++;
ans = max(ans, res);
}
}
}
cout << ans << endl;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--)
solve();
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi