更改序列
题目描述:
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;
}