結果
| 問題 | No.1767 BLUE to RED | 
| コンテスト | |
| ユーザー |  siman | 
| 提出日時 | 2021-11-29 17:25:48 | 
| 言語 | C++17(clang) (17.0.6 + boost 1.87.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 351 ms / 2,000 ms | 
| コード長 | 1,928 bytes | 
| コンパイル時間 | 1,606 ms | 
| コンパイル使用メモリ | 144,232 KB | 
| 実行使用メモリ | 17,264 KB | 
| 最終ジャッジ日時 | 2024-07-02 12:57:59 | 
| 合計ジャッジ時間 | 6,858 ms | 
| ジャッジサーバーID (参考情報) | judge5 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 21 | 
ソースコード
#include <cassert>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <limits.h>
#include <map>
#include <queue>
#include <set>
#include <string.h>
#include <vector>
using namespace std;
typedef long long ll;
struct Node {
  int a_idx;
  int b_idx;
  int dist;
  Node(int a_idx = -1, int b_idx = -1, int dist = -1) {
    this->a_idx = a_idx;
    this->b_idx = b_idx;
    this->dist = dist;
  }
  bool operator>(const Node &n) const {
    return dist > n.dist;
  }
};
int main() {
  int N, M;
  cin >> N >> M;
  vector<int> A(N);
  for (int i = 0; i < N; ++i) {
    cin >> A[i];
  }
  vector<int> B(M);
  for (int i = 0; i < M; ++i) {
    cin >> B[i];
  }
  priority_queue <Node, vector<Node>, greater<Node>> pque;
  for (int i = 0; i < N; ++i) {
    int a = A[i];
    auto it = lower_bound(B.begin(), B.end(), a);
    int idx;
    if (it == B.end()) {
      idx = B.size() - 1;
    } else {
      idx = it - B.begin();
    }
    // fprintf(stderr, "idx: %d, a: %d, b: %d\n", idx, a, B[idx]);
    pque.push(Node(i, idx, abs(a - B[idx])));
    if (0 <= idx - 1) {
      pque.push(Node(i, idx - 1, abs(a - B[idx - 1])));
    }
    if (idx + 1 < M) {
      pque.push(Node(i, idx + 1, abs(a - B[idx + 1])));
    }
  }
  bool checked[M];
  memset(checked, false, sizeof(checked));
  ll ans = 0;
  while (not pque.empty()) {
    Node node = pque.top();
    pque.pop();
    if (checked[node.b_idx]) continue;
    checked[node.b_idx] = true;
    ans += node.dist;
    // fprintf(stderr, "%d - %d\n", B[node.b_idx], node.dist);
    if (0 <= node.b_idx - 1 && not checked[node.b_idx - 1]) {
      pque.push(Node(node.a_idx, node.b_idx - 1, abs(B[node.b_idx] - B[node.b_idx - 1])));
    }
    if (node.b_idx + 1 < M && not checked[node.b_idx + 1]) {
      pque.push(Node(node.a_idx, node.b_idx + 1, abs(B[node.b_idx] - B[node.b_idx + 1])));
    }
  }
  cout << ans << endl;
  return 0;
}
            
            
            
        