NC200378. cls的字符串game
描述
要求你告诉他操作步骤,使得原串变为目标串
输入描述
输入共四行。
前三行每行代表一种操作规则,序号分别为1 2 3,每行包含两个只包含字符A和B的字符串s和t,代表该规则可以将s替换成t。
第四行包含三个元素:一个数字a,两个随机字符串S和T,a代表操作次数,S代表起始串,T代表目标串
。
输出描述
输出a行,每行包括三个元素,中间用空格隔开,代表操作步骤:
数字x和数字y,字符串P,x代表选择的操作规则(1/2/3),y代表在串中的操作位置(串第一个字符位置为1,操作位置以子串的起始位置记),P代表操作后的串。
数据保证一定有解,如果有多解,任意输出一种答案即可。
示例1
输入:
BAB A A BAA AAB BB 6 BAB BABBBBAA
输出:
1 1 A 2 1 BAA 2 3 BABAA 2 5 BABABAA 2 4 BABBAABAA 3 5 BABBBBAA
C++11(clang++ 3.9) 解法, 执行用时: 68ms, 内存消耗: 396K, 提交时间: 2020-07-02 16:43:17
#include <bits/stdc++.h> using namespace std; string a[5], b[5], s, t; int q; int r1[9], r2[9]; string r3[9]; bool dfs(int u, string s) { if (u == q) return s == t; for (int i = 0; i < 3; i++) for (int j = 0; j + a[i].size() <= s.size(); j++) { if (a[i] == s.substr(j, a[i].size())) { string w = s.substr(0, j) + b[i] + s.substr(j + a[i].size()); if (dfs(u + 1, w)) { r1[u] = i + 1, r2[u] = j + 1, r3[u] = w; return true; } } } return false; } int main() { for (int i = 0; i < 3; i++) cin >> a[i] >> b[i]; cin >> q >> s >> t; dfs(0, s); for (int i = 0; i < q; i++) cout << r1[i] << ' ' << r2[i] << ' ' << r3[i] << endl; return 0; }
C++14(g++5.4) 解法, 执行用时: 96ms, 内存消耗: 456K, 提交时间: 2019-12-13 23:10:32
#include<bits/stdc++.h> using namespace std; string a[3],b[3]; int k;string from,to; vector<pair<pair<int,int>,string>>v; void dfs(string now){ if (v.size()==k){ if (now==to){ for (auto i:v)cout<<i.first.first<<" "<<i.first.second<<" "<<i.second<<endl; exit(0); } return; } for (int i=0;i<3;i++){ int p=-1; while((p=now.find(a[i],p+1))!=-1){ string temp=now; temp.replace(p,a[i].size(),b[i]); v.push_back({{i+1,p+1},temp}); dfs(temp); v.pop_back(); } } } int main(){ for (int i=0;i<3;i++)cin>>a[i]>>b[i]; cin>>k>>from>>to; dfs(from); }