当前位置: 代码迷 >> 综合 >> Codeforces C1. Prefix Flip (Easy Version) (二进制串 / 模拟 / 构造) (Roun #658 Div.2)
  详细解决方案

Codeforces C1. Prefix Flip (Easy Version) (二进制串 / 模拟 / 构造) (Roun #658 Div.2)

热度:19   发布时间:2023-12-22 13:32:46.0

传送门

题意: 给出两个长度为n的二进制串a和b,你每次可选取一段前缀子串取反并翻转(即:10010 -> 01101 -> 10110).已知在3 * n次操作内一定能将a变成b。先让你找到一种处理方法将a变成b,且操作次数不得超过3 * n。输出处理的次数,和每次选择的前缀长度。
在这里插入图片描述
思路:

  • 既然是每次翻转整个前缀,那么意味着每次前面的字符都会发生改变,那么我们就可从后往前改变。
  • 从后往前挨个看,若当前位置和目标b该位置一样就直接考虑前一个字符。
  • 因为是取反后还要交换,所以每次的a[i]都是和a[1]在替换。若当前b[i]和a[1]一样,那么取反翻转后还是a[i] != b[i],所以我们先让a[1]取反(即让a[1]与b[i]相反)。而当a[1]与b[i]不一样时,直接前i长度的子串取反翻转即可,然后再考虑下一个位置的字符。

代码实现:

#include<bits/stdc++.h>
//#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {
    {
    1, 0}, {
    -1, 0}, {
    0, 1}, {
    0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 2e5 + 5;int t, n;
string a, b;
vector<int> vt;signed main()
{
    IOS;cin >> t;while(t --){
    a.clear(); b.clear(); vt.clear();cin >> n >> a >> b;a = 'a' + a;  b = 'b' + b;for(int i = n; i; i --){
    if(a[i] == b[i]) continue;if(a[1] == b[i]){
    if(a[1] == '1') a[1] = '0';else a[1] = '1';vt.push_back(1);}for(int j = 1; j <= i; j ++){
    if(a[j] == '1') a[j] = '0';else a[j] = '1';}reverse(a.begin() + 1, a.begin() + i + 1);vt.push_back(i);// cout << "a:" << " " << a << endl;}cout << vt.size() << " ";for(auto it : vt) cout << it << " ";cout << endl;}return 0;
}
  相关解决方案