题意:有n个绝对值各不相同的非0整数,选出尽量多的数,排成一个序列,使得正负号交替,且绝对值递增。输出最长序列长度。
思路:其实按照绝对值排序后,只要选出正负号交替最长的序列就可以了。用一个标记来表示下一个要选的是正号还是负号。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int MAXN = 500005;
struct node{
int x, y;
}a[MAXN];
int arr[MAXN], b[MAXN], order[MAXN];
int n;
int cmp(node a, node b) {
return a.y < b.y;
}
int main() {
int cas;
scanf("%d", &cas);
while (cas--) {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i].x);
if (a[i].x < 0)
a[i].y = abs(a[i].x);
else
a[i].y = a[i].x;
}
sort(a, a + n, cmp);
int cnt = 1, flag ;
if (a[0].x == a[0].y)
flag = 1;
else
flag = 0;
for (int i = 1; i < n; i++) {
if (a[i].x == a[i].y && !flag) {
flag = 1;
cnt++;
}
else if (a[i].x != a[i].y && flag) {
flag = 0;
cnt++;
}
}
printf("%d\n", cnt);
}
return 0;
}
本文探讨了在给定一组不同非零整数时,如何通过排序和选择正负号交替的方式,形成最长序列的问题,并提供了实现算法的代码示例。

455

被折叠的 条评论
为什么被折叠?



