QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#777544 | #8058. Binary vs Ternary | 22016020736 | TL | 0ms | 0kb | C++17 | 2.4kb | 2024-11-24 03:04:21 | 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;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Time Limit Exceeded
input:
3 1 111 110110 1101010 1111 111111
output:
-1