[HDU] [2020] Absolute Value Sorting

Problem Description

Loading...

Problem Analysis

Thinking back to the first time I saw this problem, I couldn’t write it…
This time it still feels a bit troublesome

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<stdio.h>
#include<algorithm>
using namespace std;
struct numm {
	int m,flag;
} a[120];
bool vs(numm A,numm B) {
	return A.m>B.m;
}
int main() {
	int n;
	while(scanf("%d",&n),n) {
		for(int i=0; i<n; i++) {
			scanf("%d",&a[i].m);
			if(a[i].m<0) {
				a[i].flag=1;
				a[i].m=-a[i].m;
			} else
				a[i].flag=0;
		}
		sort(a,a+n,vs);
		for(int i=0; i<n; i++) {
			if(a[i].flag)
				printf("-");
			printf("%d",a[i].m);
			if(i<n-1)
				printf(" ");
		}
		printf("\n");
	}
	return 0;
}

20160404 addendum:

Call sort with a custom absolute-value comparison function

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
bool cmp(int a,int b) {
	return abs(a)>abs(b);
}
int main() {
	int n;
	int a[120];
	while(scanf("%d",&n),n) {
		for(int i=0; i<n; i++)
			scanf("%d",&a[i]);
		sort(a,a+n,cmp);
		for(int i=0; i<n; i++) {
			printf("%d",a[i]);
			if(i==n-1)
				printf("\n");
			else
				printf(" ");
		}
	}
	return 0;
}

Problem link: [HDU] [2020] Absolute Value Sorting

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...