算法竞赛训练指南78页,排序
题目意思:
有n个非0的整数,要求按某种顺序排,使得这些数的绝对值从小到大,而且
正数和负数间隔排列。
本题要点:
1、用结构体 node 来记录每一个数的绝对值 和正负, 按绝对值排序,
然后从左到右扫描,找出正负相隔的一个数列。
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int MaxN = 500010;
int T, n;
struct node
{
int val;
int flag;
bool operator<(const node & rhs) const
{
return abs(val) < abs(rhs.val);
}
}pos[MaxN];
void solve()
{
sort(pos, pos + n);
int cur = pos[0].flag, ans = 1;
for(int i = 1; i < n; ++i)
{
if((pos[i].flag ^ cur) == 1) //不同
{
cur = pos[i].flag;
++ans;
}
}
printf("%d\n", ans);
}
int main()
{
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
for(int i = 0; i < n; ++i)
{
scanf("%d", &pos[i].val);
if(pos[i].val > 0)
{
pos[i].flag = 1;
}else{
pos[i].flag = 0;
}
}
solve();
}
return 0;
}
/*
2
5
7
-2
6
9
-3
8
11
-9
2
5
18
17
-15
4
*/
/*
2
5
*/