알고리즘/문제풀이

7902 : 등수 매기기 - JAVA

mm______m 2024. 5. 31. 16:36

https://www.acmicpc.net/problem/2012

 

 

abs를 사용하는 문제이다. 수를 정렬하고 원래 등수와 차이나는 등수만큼 절댓값 연산을 수행한 누적합을 출력한다.

 

import java.util.*;
import java.io.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] arr = new int[n];
		long res = 0;
		for(int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		Arrays.sort(arr);
		for(int i = 1; i <= n; i++) {
			res += Math.abs(i-arr[i-1]);
		}
		System.out.println(res);
	}
}