|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.IOException; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.util.ArrayDeque; |
| 5 | +import java.util.Deque; |
| 6 | +import java.util.HashSet; |
| 7 | +import java.util.StringTokenizer; |
| 8 | + |
| 9 | +public class SB_18513 { |
| 10 | + static int N, K; |
| 11 | + static Deque<Node> que = new ArrayDeque<>(); |
| 12 | + static HashSet<Integer> set = new HashSet<>(); |
| 13 | + static int[] dir = new int[]{-1, 1}; |
| 14 | + |
| 15 | + private static long bfs() { |
| 16 | + long cnt = 0; |
| 17 | + |
| 18 | + int check = 0; |
| 19 | + while (!que.isEmpty()) { |
| 20 | + Node cur = que.poll(); |
| 21 | + |
| 22 | + for (int d : dir) { |
| 23 | + int nxt = cur.i + d; |
| 24 | + if (set.contains(nxt)) continue; |
| 25 | + cnt+= cur.v+1; |
| 26 | + set.add(nxt); |
| 27 | + que.offer(new Node(nxt, cur.v + 1)); |
| 28 | + check++; |
| 29 | + |
| 30 | + if (check==K) return cnt; |
| 31 | + } |
| 32 | + } |
| 33 | + return cnt; |
| 34 | + } |
| 35 | + |
| 36 | + public static void main(String[] args) throws IOException { |
| 37 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 38 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 39 | + N = Integer.parseInt(st.nextToken()); |
| 40 | + K = Integer.parseInt(st.nextToken()); |
| 41 | + |
| 42 | + st = new StringTokenizer(br.readLine()); |
| 43 | + for (int i = 0; i < N; i++) { |
| 44 | + int idx = Integer.parseInt(st.nextToken()); |
| 45 | + que.offer(new Node(idx, 0)); |
| 46 | + set.add(idx); |
| 47 | + } |
| 48 | + |
| 49 | + System.out.println(bfs()); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +class Node { |
| 54 | + int i, v; |
| 55 | + public Node(int i, int v) { |
| 56 | + this.i = i; |
| 57 | + this.v = v; |
| 58 | + } |
| 59 | +} |
0 commit comments