您的位置:首页 > 产品设计 > UI/UE

UVA11039- Building designing

2014-08-06 21:33 197 查看
题意:有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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: