题目链接:点击打开链接
题目大意: 有n个绝对值各不相同的非0整数,选出尽量多的数,使得正负交替且绝对值递增.
思路: 数学分析
分析:
1. 将数字按绝对值大小排序
2. 遍历序列,将符号不满足的数字删除
代码:
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 500000 + 10;
bool cmp(int a, int b)
{
return abs(a) < abs(b);
}
bool different_sign(int a, int b)
{
int c = a / abs(a);
int d = b / abs(b);
return c * d < 0;
}
int main()
{
int kase, n, floor[maxn];
scanf("%d", &kase);
while (kase--)
{
scanf("%d", &n);
for (int i = 0; i < n; ++i)
scanf("%d", &floor[i]);
sort(floor, floor+n, cmp);
int ans = n, pos = 0;
for (int i = 1; i < n; ++i)
{
if (different_sign(floor[pos], floor[i]))
pos = i;
else
--ans;
}
printf("%d\n", ans);
}
return 0;
}