Codeforces C2. Prefix Flip (Hard Version)(二进制串 / 模拟) (Round #658 Div.2)

传送门

题意: 其实这就是C1题的加强版,只不过C1的字符长度是1000且操作次数不得 > 3n,而C2的字符长度是1e5且操作次数不得 > 2n,且T都是一样为1000.
在这里插入图片描述
思路:

  • 现在的时间复杂度为O(n * t) = 1e8,堪堪能过,因此实际的翻转操作便不再可取了。
  • 我们先将a全部翻转成同一字符(当然就是a的最后一个字符),由于同一字符取反后还是一致的,所以取反便不再有意义。
  • 因为答案只需要进行操作的位置,所以再按照b字符串从后往前开始匹配对a的前缀进行取反,当然过程中并不用真正的取反,只需要用一个变量tmp记录一下当前a的字符类型进行取反即可。
  • 这样下来就相当于最多进行2n次操作(a进行n从,b进行n次)。

代码实现:

#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 --){
        cin >> n >> a >> b;
        if(a == b){
            cout << 0 << endl;
            continue;
        }
        a = 'a' + a;  b = 'b' + b;
        char tmp = a[n]; vt.clear();
        for(int i = 1; i < n; i ++)
            if(a[i] != a[i+1]) vt.push_back(i);
        for(int i = n; i; i --)
            if(b[i] != tmp) tmp = b[i], vt.push_back(i);
        cout << vt.size() << " ";
        for(auto it : vt) cout << it << " ";
        cout << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Satur9/article/details/107541144