UVA 11039 Building designing(算法竞赛训练指南,排序)

算法竞赛训练指南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
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值