HDU-2020 Absolute Sort

本文详细解析了一种基于绝对值的排序算法,该算法首先将输入的整数转换为正数并进行排序,然后根据原始数值的正负性恢复排序后的结果。适用于处理包含正负数的整数集合,确保了排序后的列表中元素的绝对值递增。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

See the article on https://dyingdown.github.io/2019/12/20/HDU-2020%20Absolute-Sort/

Absolute Sort

Input n (n <= 100) integers, and output them after sorting according to the absolute value. The title guarantees that for each test case, the absolute values of all numbers are not equal.

Input

There are multiple groups of input data. Each group occupies one line. The first number of each line is n, followed by n integers. N = 0 means the end of the input data. No processing is performed.

Output

For each test instance, the sorted results are output, separated by a space between the two numbers. One line per test instance.

Sample Input

3 3 -4 2
4 0 1 2 -3
0

Sample Output

-4 3 2
-3 2 1 0

Analysis

Turn then into positive numbers and sort. And for each unit in array, if it’s negative originally, turn it back to negative.

Code

#include<bits/stdc++.h>

using namespace std;

map<int,int> a;
int arr[1000];
int main() {
	int n;
	while(cin >> n, n){
		for(int i = 0; i < n; i ++) {
			cin >> arr[i];
			if(arr[i] >= 0) a[abs(arr[i])] = 0;
			else a[abs(arr[i])] = 1;
			arr[i] = abs(arr[i]);
		}
		sort(arr, arr + n, greater<int>());
		for(int i = 0; i < n; i ++) {
			if(a[arr[i]]) cout << '-' << arr[i];
			else cout << arr[i];
			if(i != n - 1) cout << " ";
			else cout << endl;
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值