15分RE+TLE求调
查看原帖
15分RE+TLE求调
862592
__sunhy2012__楼主2025/1/22 19:23
#include <iostream>
#include <queue>
#include <unordered_set>
#include <string>

using namespace std;

// 定义状态结构体
struct State {
    string num;
    int steps;
    State(string n, int s) : num(n), steps(s) {}
};

// 循环右移函数
string rotateRight(const string& num) {
    if (num.size() == 1) return num;
    string rotated = num.substr(1) + num[0];
    while (rotated.size() > 1 && rotated[0] == '0') {
        rotated = rotated.substr(1);
    }
    return rotated;
}

// BFS函数
int bfs(const string& start) {
    queue<State> q;
    unordered_set<string> visited;
    q.push(State(start, 0));
    visited.insert(start);

    while (!q.empty()) {
        State current = q.front();
        q.pop();

        if (current.num == "1") {
            return current.steps;
        }

        // 操作1:加1
        string nextNum1 = to_string(stoi(current.num) + 1);
        if (visited.find(nextNum1) == visited.end()) {
            q.push(State(nextNum1, current.steps + 1));
            visited.insert(nextNum1);
        }

        // 操作2:循环右移
        string nextNum2 = rotateRight(current.num);
        if (visited.find(nextNum2) == visited.end()) {
            q.push(State(nextNum2, current.steps + 1));
            visited.insert(nextNum2);
        }
    }

    return -1; // 理论上不会到达这里
}

int main() {
    string n;
    cin >> n;
    cout << bfs(n) << endl;
    return 0;
}

@General0826

2025/1/22 19:23
加载中...