QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#777544#8058. Binary vs Ternary22016020736TL 0ms0kbC++172.4kb2024-11-24 03:04:212024-11-24 03:04:21

Judging History

你现在查看的是最新测评结果

  • [2024-11-24 03:04:21]
  • 评测
  • 测评结果:TL
  • 用时:0ms
  • 内存:0kb
  • [2024-11-24 03:04:21]
  • 提交

answer

#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
#include <string>
#include<bits/stdc++.h>
using namespace std;

// Function to convert a ternary string to a binary string
string ternaryToBinary(const string &s) {
    int ternaryValue = 0;
    for (char c : s) {
        ternaryValue = ternaryValue * 3 + (c - '0');
    }
    string binary = "";
    while (ternaryValue > 0) {
        binary = char((ternaryValue % 2) + '0') + binary;
        ternaryValue /= 2;
    }
    return binary.empty() ? "0" : binary;
}

// Function to perform the transformation and check if we can reach B from A
bool canTransform(string A, string B, vector<pair<int, int>> &operations) {
    queue<pair<string, int>> q;
    unordered_map<string, pair<int, int>> parent;
    q.push({A, 0});
    parent[A] = {-1, -1};

    while (!q.empty()) {
        auto [current, steps] = q.front();
        q.pop();

        if (current == B) {
            // Reconstruct the path
            string temp = B;
            while (temp != A) {
                auto [l, r] = parent[temp];
                operations.push_back({l, r});
                temp = temp.substr(0, l - 1) + temp.substr(r);
            }
            reverse(operations.begin(), operations.end());
            return true;
        }

        if (steps >= 512) continue;

        for (int l = 1; l <= current.length(); ++l) {
            for (int r = l; r <= current.length(); ++r) {
                string sub = current.substr(l - 1, r - l + 1);
                string newSub = ternaryToBinary(sub);
                string newStr = current.substr(0, l - 1) + newSub + current.substr(r);

                if (newStr.length() > 128) continue;

                if (parent.find(newStr) == parent.end()) {
                    parent[newStr] = {l, r};
                    q.push({newStr, steps + 1});
                }
            }
        }
    }

    return false;
}

int main() {
    int T;
    cin >> T;

    while (T--) {
        string A, B;
        cin >> A >> B;

        vector<pair<int, int>> operations;
        if (canTransform(A, B, operations)) {
            cout << operations.size() << "\n";
            for (const auto &op : operations) {
                cout << op.first << " " << op.second << "\n";
            }
        } else {
            cout << "-1\n";
        }
    }

    return 0;
}

详细

Test #1:

score: 0
Time Limit Exceeded

input:

3
1
111
110110
1101010
1111
111111

output:

-1

result: