3377. Digit Operations to Make Two Integers Equal

3377. Digit Operations to Make Two Integers Equal

Description

You are given two integers n and m that consist of the same number of digits.

You can perform the following operations any number of times:

  • Choose any digit from n that is not 9 and increase it by 1.
  • Choose any digit from n that is not 0 and decrease it by 1.

The integer n must not be a prime number at any point, including its original value and after each operation.

The cost of a transformation is the sum of all values that n takes throughout the operations performed.

Return the minimum cost to transform n into m. If it is impossible, return -1.

Example 1:

1
2
3
Input: n = 10, m = 12

Output: 85

Explanation:

We perform the following operations:

  • Increase the first digit, now n = 20.
  • Increase the second digit, now n = 21.
  • Increase the second digit, now n = 22.
  • Decrease the first digit, now n = 12.

Example 2:

1
2
3
Input: n = 4, m = 8

Output: -1

Explanation:

It is impossible to make n equal to m.

Example 3:

1
2
3
Input: n = 6, m = 2

Output: -1

Explanation:

Since 2 is already a prime, we can’t make n equal to m.

Constraints:

  • 1 <= n, m < 10^4
  • n and m consist of the same number of digits.

Hints/Notes

  • 2024/12/10
  • dijkstra’s algorithm
  • pre-calculate the prime numbers
  • 0x3F’s solution(checked)
  • Biweekly Contest 145

Solution

Language: C++

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
const int MX = 10000;
bool np[MX];

int init = [] {
np[1] = true;
for (int i = 2; i < MX; i++) {
if (!np[i]) {
for (int j = i * i; j < MX; j += i) {
np[j] = true;
}
}
}
return 0;
}();

class Solution {
public:
int minOperations(int n, int m) {
int res = 0;
if (!np[n] || !np[m]) {
return -1;
}
int len = to_string(n).size();
vector<int> dis(pow(10, len), INT_MAX);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
pq.emplace(n, n);
while (!pq.empty()) {
auto [dis_x, x] = pq.top();
pq.pop();
if (x == m) {
return dis_x;
}
if (dis[x] < dis_x) {
continue;
}
int pow10 = 1;
for (int v = x; v; v /= 10) {
int d = v % 10;
if (d > 0) {
int y = x - pow10;
int dis_y = dis_x + y;
if (np[y] && dis_y < dis[y]) {
pq.emplace(dis_y, y);
dis[y] = dis_y;
}
}
if (d < 9) {
int y = x + pow10;
int dis_y = dis_x + y;
if (np[y] && dis_y < dis[y]) {
pq.emplace(dis_y, y);
dis[y] = dis_y;
}
}
pow10 *= 10;
}
}
return -1;
}
};