码迷,mamicode.com
首页 > 编程语言 > 详细

uva 11039 Building designing (排序)

时间:2015-01-31 12:39:51      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:uva   c语言   

                       uva 11039 Building designing


An architect wants to design a very high building. The building will consist of some floors, and each floor has a certain size. The size of a floor must be greater than the size of the floor immediately above it. In addition, the designer (who is a fan of a famous Spanish football team) wants to paint the building in blue and red, each floor a colour, and in such a way that the colours of two consecutive floors are different.

To design the building the architect has n available floors, with their associated sizes and colours. All the available floors are of different sizes. The architect wants to design the highest possible building with these restrictions, using the available floors.

Input 

The input file consists of a first line with the number p of cases to solve. The first line of each case contains the number of available floors. Then, the size and colour of each floor appear in one line. Each floor is represented with an integer between -999999 and 999999. There is no floor with size 0. Negative numbers represent red floors and positive numbers blue floors. The size of the floor is the absolute value of the number. There are not two floors with the same size. The maximum number of floors for a problem is 500000.

Output 

For each case the output will consist of a line with the number of floors of the highest building with the mentioned conditions. 

Sample Input 

 
2
5
7
-2
6
9
-3
8
11
-9
2
5
18
17
-15
4

Sample Output 

 
2
5


题目大意:n个绝对值各不相同的非0整数,选出尽量多的数,排成一个序列,使得正负号交替且绝对值递增。

解题思路:先将所有数按照绝对值大小排序,然后依次交替寻找正负数。


#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
int num[500005];
int cmp(int a, int b) {
	return abs(a) < abs(b);
}
int main() {
	int T;
	scanf("%d", &T);
	while (T--) {
		int n;
		scanf("%d", &n);
		for (int i = 0; i < n; i++) {
			scanf("%d", &num[i]);
		}
		sort(num, num + n, cmp);
		int ans = 0, flag = 0;
		for (int i = 0; i < n; i++) {
			if (!flag) { //第一个数,flag标记正负
				if (num[i] > 0) flag = 1;
				else flag = 2;
				ans++;
				continue;
			}
			if (flag == 1) { //上一个数为正,当前数为负
				if (num[i] < 0) {
					flag = 2;
					ans++;
					continue;
				}
			}
			if (flag == 2) { //上一个数为负。当前数为正
				if (num[i] > 0) {
					flag = 1;
					ans++;
					continue;
				}
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}





uva 11039 Building designing (排序)

标签:uva   c语言   

原文地址:http://blog.csdn.net/llx523113241/article/details/43339051

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!