UVALive 6832

更改序列

题目描述:

N《=15,给出一个1 0串,为初始串,给出一个目标串,操作只有一个,就是交换相邻的两个数字,问初始串变成目标串的最少操作次数。其中目标串给出的方式是:比如1001011 方式为:1 2 1 1 2 这样的对应两个串,挑出一个操作最少的就好。

题解:

我是想:先把目标串变成两个跑两次,对于每个串,先看1的个数,然后从第一个开始扫,因为只能交换相邻的,所以当前不行就从后面找,一直交换。轩哥的代码没有看。。。求帮助QAQ

重点:

只能交换相邻的,那么就保证前面的一直是对的,然后交换只能往后面找。

代码:
//轩哥的代码
#include <cstdio>
#include <algorithm>
using namespace std;
int a[32], b[32], p[32], n, m;

int solve() {
    int pos = 1, rpos = 0, ans = 0, t = 1;
    while (pos < n) {
        if(a[pos] == a[pos-1]) {
            if (t == b[rpos]) {
                int tmp = pos+1;
                while (tmp < n && a[tmp] == a[pos])
                    tmp++;
                if (tmp == n)
                    return 1000000000;
                ans += tmp - pos;
                a[tmp] = a[tmp] ^ 1;
                a[pos] = a[pos] ^ 1;
                t = 1;
                rpos++;
            }
            else {
                t++;
            }
        }
        else {
            if (t < b[rpos]) {
                int tmp = pos+1;
                while (tmp < n && a[tmp] == a[pos])
                    tmp++;
                if (tmp == n)
                    return 1000000000;
                ans += tmp - pos;
                a[tmp] = a[tmp] ^ 1;
                a[pos] = a[pos] ^ 1;
                t++;
            }
            else {
                t = 1;
                rpos++;
            }
        }
        //printf("----pos%d --rpos%d -----a[pos]%d ----t%d-----ans%d\n", pos, rpos, a[pos], t, ans);
        pos++;

    }
    if (t == b[rpos])
        return ans;
    else 
        return 1000000000;
}
int main() {
    while (~scanf("%d%d", &n, &m)) {
        for (int i = 0; i < n; ++i) {
            scanf("%d", &a[i]);
            p[i] = a[i];
        }
        for (int i = 0; i < m; ++i)
            scanf("%d", &b[i]);
        int ans = solve();
        for (int i = 0; i < n; ++i)
            a[i] = p[i];
        int l = 1;
        while (a[l] == a[l-1] && l < n)
            l++;
        if (l < n) {
            a[0] ^= 1;
            a[l] ^= 1;
            ans = min(solve() + l, ans);
        }
        printf("%d\n", ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值