时间轴

2025-10-19

init


题目:

DFS枚举:

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
#include <string>
#include <unordered_set>
#include <algorithm>
#include <queue>

using std::string;
using std::unordered_set;
using std::queue;

class Solution {
private:
void sadd(string &s, int a)
{
int i, n;
n = s.size();
for (i = 1; i < n; i += 2) {
s[i] = ((s[i] - '0') + a) % 10 + '0';
}
}

void sshift(string &s, int b)
{
int n = s.size();
b = b % n;

string substr = s.substr(n - b, b);

s.erase(s.end() - b, s.end());
s.insert(s.begin(), substr.begin(), substr.end());
}

public:
string findLexSmallestString(string s, int a, int b)
{
unordered_set<string> visited;
queue<string> q;
string res = s, cur, t;

q.push(s);
visited.insert(s);
// BFS
while (!q.empty()) {
cur = q.front();
q.pop();
res = min(res, cur);
// 两条分支累加或者轮转

// 累加操作
t = cur;
sadd(t, a);
if (!visited.count(t)) {
visited.insert(t);
q.push(t);
}

// 轮转操作
t = cur;
sshift(t, b);
if (!visited.count(t)) {
visited.insert(t);
q.push(t);
}
}

return res;
}
};