Home BOJ. Match The Numbers (2494)
Post
Cancel

BOJ. Match The Numbers (2494)

[Link] https://www.acmicpc.net/problem/2494


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstring>
#include <stack>
#include <cmath>
// #include <bits/stdc++.h>
using namespace std;
#define FASTIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define command_param int argc, char *argv[]
#define for0(i, n) for(int i = 0; i < n; i++)
#define for1(i, n) for(int i = 1; i < n; i++)
#define fori(s, e) for(int i = s; i < e; i++)
#define ll long long
#define endl "\n"
#define nulls '\0'
#define dkdk " "

const int INF = 987654321;

// char mm[100][100];
int di[4] = { -1, 0, 1, 0 };
int dj[4] = { 0, 1, 0, -1 };
int t, n, m, x, d;

string src, des;
int inc = 0;
int dp[10000][10];
pair<int,int> parent_and_rot[10000][10];
int ans[10000];

int pre(int val) {
  int quo = val / 10;
  int ans = val - 10 * quo;
  if(ans >= 0) return ans;
  return ans + 10;
}

int main(int argc, char *argv[]) {
  FASTIO;
  cin >> n >> src >> des;
  for0(i, n) for0(j, 10) dp[i][j] = INF;
  int src_num = src[0]-'0', des_num = des[0] - '0', rot, cur_num;
  rot = des_num-src_num;
  if(rot < 0) rot+=10;
  if(rot) {
    dp[0][rot] = rot, dp[0][0] = 10 - rot;
    parent_and_rot[0][rot] = { -1, rot };
    parent_and_rot[0][0] = { -1, rot - 10 };
  } else dp[0][0] = 0, parent_and_rot[0][0] = { -1, 0 };
  for1(i, n) {
    src_num = src[i]-'0', des_num = des[i] - '0';
    for0(j, 10) {
      if(dp[i-1][j] == INF) continue;
      cur_num = pre(src_num + j), rot;
      rot = des_num-cur_num;
      if(rot < 0) rot+=10;
      if(dp[i][pre(j + rot)] > dp[i-1][j] + rot) {
        dp[i][pre(j + rot)] = dp[i-1][j] + rot;
        parent_and_rot[i][pre(j+rot)] = { j, rot };
      }
      if(dp[i][j] > dp[i-1][j] + 10 - rot) {
        dp[i][j] = dp[i-1][j] + 10 - rot;
        parent_and_rot[i][j] = { j, rot - 10 };
      }
    }
  }
  int minv = INF, rot_idx = 0;
  for0(i, 10) if(minv > dp[n-1][i]) { minv = dp[n-1][i]; rot_idx = i; };
  cout << minv << endl;
  for(int i = n-1; i>=0; i--) {
    ans[i] = parent_and_rot[i][rot_idx].second;
    rot_idx = parent_and_rot[i][rot_idx].first;
  }
  for0(i, n) {
    cout << i+1 << " " << ans[i] << endl;
  }
  return 0;
}
This post is licensed under CC BY 4.0 by the author.