Codeforces Round #658 (Div. 2) C.Prefix Flip(思维,贪心)

题目传送
题意:
给你俩个长度为n的二进制字符串a,b,现在你可以进行操作:翻转字符串a的任意前缀,(0变成1,1变成0),然后把翻转后的前缀再倒序,现在你最多有2*n次这个操作,让你打印怎么操作的,使得字符串a等于b

思路:
贪心一下,先把字符串a全部变成0或者1(至于是0还是1不重要)

		string a,b;
        cin >> a >> b;
        a = " " + a,b = " " + b;
        vector<int> v;
        for(int i = 2;i <= n;i++)
            if(a[i] != a[i-1])
                v.push_back(i-1);

然后就是如何变成字符串b了,我们想想,现在字符串a全是0或者1,那么我们用一个字符存他是哪种,然后我们从字符串b的最后一位开始变,如果现在字符串b上的这一位不同于存的那位,那么我们就直接变到这一位的前缀,然后注意的是,现在的这一位以前的字符在翻转后还是相同的(都是0或者1),然后再依次进行上述操作。

AC代码

#include <bits/stdc++.h>
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 2e5 + 5;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const int mod = 1e9+7;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
signed main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    //    freopen("input.txt","r",stdin);
    //    freopen("output.txt","w",stdout);
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;
        string a,b;
        cin >> a >> b;
        a = " " + a,b = " " + b;
        vector<int> v;
        for(int i = 2;i <= n;i++)
            if(a[i] != a[i-1])
                v.push_back(i-1);
        b[n+1] = a[n];//存一位
        for(int i = n;i >= 1;i--)
            if(b[i] != b[i+1])//比较是否需要翻转
                v.push_back(i);
        cout << v.size() << " ";
        for(int i = 0;i < v.size();i++)
            cout << v[i] << " ";
        cout << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/moasad/article/details/107513874