Computer Science/Algorithm

[Algorithm/C] codeground 정수 정렬하기(10000)

재오니소스 2018. 4. 29. 13:15

N개의 정수가 주어졌을 때 오름차순으로 정렬한 후 아래와 같은 작업을 하는 프로그램을 작성하시오.

 

1. N개의 정수를 오름차순으로 정렬한다.

    (오름차순 :  값이 작은 쪽에서부터 큰 쪽으로의 순서를 말함.)

 

2. 정렬한 숫자로 아래와 같은 작업을 한다. Ai

 

3. A1 - A2 + A3 - A4 ... + A2i-1 - A2i

 

4. 위 식의 결과값을 출력한다.

 

 

예를 들자면 입력값이

 

N = 5

 

Ai = 3,5,1,8,4 일때

 

정렬을 하게 되면 1, 3, 4, 5, 8 이 된다.

 

이를 계산하면 1-3+4-5+8 = 5 가 된다.

 

ㅡ 제한시간 : 전체 테스트케이스는 50개 이하이며, 전체 수행시간은 1초 이내(Java 2초 이내)

 

 

입력

입력 파일에는 여러 테스트 케이스가 포함될 수 있다.

파일의 첫째 줄에는 테스트 케이스의 개수를 나타내는 자연수 T가 주어지고,

이후 차례로 T개의 테스트 케이스가 주어진다. ( 1≤ T ≤ 50)

각 테스트 케이스의 첫 줄에는 숫자의 개수를 나타내는 N이 주어진다. . ( 1≤ N ≤ 10000)

다움 N개의 줄에는 각각의 숫자 Ai가 주어진다. (( 0≤ Ai ≤ 10,000,000 )

출력

각 테스트 케이스의 답을 순서대로 표준출력으로 출력하여야하며,

각 테스트 케이스마다 첫 줄에는 "Case #T" 를 출력하여야 한다. 이때 T는 테스트 케이스 번호이다.

그 다음 줄에는 정답을 출력한다.

입출력예

입력        출력

2

3

3

2

1

5

1

3

4

5

8

Case #1

2

Case #2

5


/*

Problem : 정수정렬하기

Writer : JaeIn Mun

Final revision : 2018.04.29

Reference : 

https://www.codeground.org

http://jaeonysos.tistory.com

*/


#include <stdio.h>

#include <stdlib.h>


int Answer;



int comp(const void *a, const void *b) {

const int *m, *n;

m = (int *)a;

n = (int *)b;


if (*m < *n) {

return -1;

}

else if (*m == *n) {

return 0;

}

else {

return 1;

}

}


int main(void)

{

int T, test_case;

/*

The freopen function below opens input.txt file in read only mode, and afterward,

the program will read from input.txt file instead of standard(keyboard) input.

To test your program, you may save input data in input.txt file,

and use freopen function to read from the file when using scanf function.

You may remove the comment symbols(//) in the below statement and use it.

But before submission, you must remove the freopen function or rewrite comment symbols(//).

*/

// freopen("input.txt", "r", stdin);


/*

If you remove the statement below, your program's output may not be rocorded

when your program is terminated after the time limit.

For safety, please use setbuf(stdout, NULL); statement.

*/

setbuf(stdout, NULL);


scanf("%d", &T);

for (test_case = 0; test_case < T; test_case++)

{

int N;

int *arr=NULL;

int sum = 0;

scanf("%d", &N);

arr = (int*)malloc(sizeof(int)*(N+1));


for (int i = 0; i < N; i++) {

scanf("%d", &arr[i]);

}


qsort(arr, N, sizeof(int), comp);



for (int i = 0; i < N; i++) {

printf("%d ", arr[i]);

}printf("\n");


for (int i = 0; i < N; i++) {

if ((i+1) % 2 != 0) {

arr[i+1] = (-1)*arr[i+1];

}

}


for (int i = 0; i < N ; i++) {

printf("%d ", arr[i]);

}printf("\n");


for (int i = 0; i < N; i++) {

sum += arr[i];

}


// Print the answer to standard output(screen).

Answer = sum;

printf("Case #%d\n", test_case + 1);

printf("%d\n", Answer);

free(arr);

}


return 0;//Your program should return 0 on normal termination.

}