|
| 1 | +```java |
| 2 | + |
| 3 | +import java.awt.Point; |
| 4 | +import java.io.BufferedReader; |
| 5 | +import java.io.IOException; |
| 6 | +import java.io.InputStreamReader; |
| 7 | +import java.util.*; |
| 8 | + |
| 9 | +public class Main { |
| 10 | + |
| 11 | + static class Node{ |
| 12 | + int idx; |
| 13 | + int x,y; |
| 14 | + public Node(int idx, int x, int y) { |
| 15 | + this.idx = idx; |
| 16 | + this.x = x; |
| 17 | + this.y = y; |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + static int nodeCnt; |
| 22 | + static Node[] nodes; |
| 23 | + static int[] ans; |
| 24 | + static List<Point> list; |
| 25 | + |
| 26 | + static StringBuilder sb = new StringBuilder(); |
| 27 | + |
| 28 | + public static void main(String[] args) throws NumberFormatException, IOException { |
| 29 | + init(); |
| 30 | + process(); |
| 31 | + print(); |
| 32 | + |
| 33 | + } |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | + public static void init() throws NumberFormatException, IOException { |
| 38 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 39 | + nodeCnt = Integer.parseInt(br.readLine()); |
| 40 | + nodes = new Node[nodeCnt]; |
| 41 | + ans = new int[nodeCnt]; |
| 42 | + for (int i = 0; i < nodeCnt; i++) { |
| 43 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 44 | + int x = Integer.parseInt(st.nextToken()); |
| 45 | + int y = Integer.parseInt(st.nextToken()); |
| 46 | + nodes[i] = new Node(i, x,y); |
| 47 | + |
| 48 | + } |
| 49 | + |
| 50 | + } |
| 51 | + |
| 52 | + public static void process() throws IOException { |
| 53 | + |
| 54 | + Arrays.fill(ans, Integer.MAX_VALUE); |
| 55 | + |
| 56 | + list = new ArrayList<>(); // 모든 후보 지점 리스트 |
| 57 | + for (int i = 0; i < nodeCnt; i++) { |
| 58 | + for (int j = 0; j < nodeCnt; j++) { |
| 59 | + list.add(new Point(nodes[i].x, nodes[j].y)); |
| 60 | + } |
| 61 | + } |
| 62 | + calculte(); |
| 63 | + |
| 64 | + |
| 65 | + for (int i = 0; i < nodeCnt; i++) { |
| 66 | + sb.append(ans[i]).append(" "); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private static void calculte() { |
| 71 | + for (Point p: list) { |
| 72 | + int x =p.x; |
| 73 | + int y = p.y; |
| 74 | + |
| 75 | + PriorityQueue<Node> pq = new PriorityQueue<>( |
| 76 | + (a,b) -> (Math.abs(x - a.x) + Math.abs(y - a.y)) - (Math.abs(x - b.x) + Math.abs(y - b.y)) ); |
| 77 | + for (Node n: nodes) pq.add(n); |
| 78 | + |
| 79 | + int distanceSum = 0; |
| 80 | + for (int i = 0; i < nodeCnt; i++) { |
| 81 | + Node n = pq.poll(); |
| 82 | + distanceSum += Math.abs(x - n.x) + Math.abs(y - n.y); |
| 83 | + |
| 84 | + ans[i] = Math.min(ans[i], distanceSum); |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + |
| 90 | + |
| 91 | + |
| 92 | + |
| 93 | + public static void print() { |
| 94 | + System.out.println(sb.toString()); |
| 95 | + |
| 96 | + } |
| 97 | +} |
| 98 | +``` |
0 commit comments