AtCoder AT_abc413_d [ABC413D] Make Geometric Sequence
题目大意
给定一个长度为 N N N 的序列 A A A,判断是否存在一个排列使其为等比数列。
思路
观察等比数列,发现其每一项的绝对值都是有序的,所以考虑对绝对值进行从小到大的排序,然后判断邻项比是否相等。但是,当我们把代码交上去时,会发现无法通过。
于是,我举出了一个样例:
1
5
-1 -1 -1 1 1
正确的输出应是 Yes
,然而程序输出了 No
,因为代码不能处理公比为 -1
的一些情况。既然如此,我们加上一段特判代码:
if (绝对值都相等)
{计算正数和负数的个数if (全是正数 || 全是负数 || abs(正数 - 负数) <= 1)Yeselse No
}
顺便说一下,作者考场上写代码时 abs
那三个字母神奇地消失了,代码怎么也调不过……
代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;int t, n;
long long a[200010];bool cmp(long long x, long long y)
{return abs(x) < abs(y);
}bool check()
{for (int i = 2; i <= n; i++)if (abs(a[i]) != abs(a[1]))return false;return true;
}int main()
{cin >> t;while (t--){cin >> n;for (int i = 1; i <= n; i++)cin >> a[i];if (check()){int cnt1 = 0, cnt2 = 0;for (int i = 1; i <= n; i++){if (a[i] > 0)cnt1++;else cnt2++;}if (cnt1 == n || cnt2 == n || abs(cnt1 - cnt2) <= 1)cout << "Yes" << endl;else cout << "No" << endl;continue;}sort(a + 1, a + n + 1, cmp);bool flag = true;for (int i = 3; i <= n; i++)if (a[i] * a[1] != a[2] * a[i - 1]){flag = false;break;}if (flag) cout << "Yes" << endl;else cout << "No" << endl;}return 0;
}