暴力啊,先随便乱分,然后算A和C的差值,然后枚举所有可以让差值变小的两个数进行交换,注意可能会在枚举中陷入死循环,设置一个标记跳出就行。
Code:
#include <bits/stdc++.h>
using namespace std;
int a[5005], c[5005], flag[5005];
set<int>aa1, cc1, ac1, other1, aa2, cc2, ac2, other2;
vector<int>ans;
int main()
{
int n;
char ch;
scanf("%d", &n);
getchar();
for (int i = 1; i <= n; i++)
{
scanf("%c", &ch);
c[i] = ch - '0';
}
getchar();
for (int i = 1; i <= n; i++)
{
scanf("%c", &ch);
a[i] = ch - '0';
}
int cc = 0, aa = 0, ac = 0, other = 0;
//flag 1 2 3 4
for (int i = 1; i <= n; i++)
{
if (c[i] == 1)
{
if (a[i])
{
ac++;
flag[i] = 3;
}
else
{
cc++;
flag[i] = 1;
}
}
else
{
if (a[i])
{
aa++;
flag[i] = 2;
}
else
{
other++;
flag[i] = 4;
}
}
}
int num1 = 0, num2 = 0;
for (int i = 1; i <= n / 2; i++)
{
switch (flag[i])
{
case 1:cc1.insert(i);break;
case 2:aa1.insert(i); num1++; break;
case 3:ac1.insert(i); num1++; break;
case 4:other1.insert(i); break;
}
}
for (int i = n / 2 + 1; i <= n; i++)
{
switch (flag[i])
{
case 1:cc2.insert(i); num2++; break;
case 2:aa2.insert(i); break;
case 3:ac2.insert(i); num2++; break;
case 4:other2.insert(i); break;
}
}
int cnt = 0;
while (num1 < num2 && cnt++ < 10000)
{
if (other1.size() != 0)
{
if (aa2.size() != 0)
{
num1++;
aa1.insert(*aa2.begin());
aa2.erase(aa2.begin());
other2.insert(*other1.begin());
other1.erase(other1.begin());
}
else if (cc2.size() != 0)
{
num2--;
cc1.insert(*cc2.begin());
cc2.erase(cc2.begin());
other2.insert(*other1.begin());
other1.erase(other1.begin());
}
else if (ac2.size() != 0 && num1 + 2 <= num2)
{
num1++;
num2--;
ac1.insert(*ac2.begin());
ac2.erase(ac2.begin());
other2.insert(*other1.begin());
other1.erase(other1.begin());
}
}
if (num1 == num2)
break;
if (cc1.size() != 0)
{
if (ac2.size() != 0)
{
num1++;
ac1.insert(*ac2.begin());
ac2.erase(ac2.begin());
cc2.insert(*cc1.begin());
cc1.erase(cc1.begin());
}
}
}
cnt = 0;
while (num2 < num1 && cnt++ < 10000)
{
if (other2.size() != 0)
{
if (cc1.size() != 0)
{
num2++;
cc2.insert(*cc1.begin());
cc1.erase(cc1.begin());
other1.insert(*other2.begin());
other2.erase(other2.begin());
}
else if (aa1.size() != 0)
{
num1--;
aa2.insert(*aa1.begin());
aa1.erase(aa1.begin());
other1.insert(*other2.begin());
other2.erase(other2.begin());
}
else if (ac1.size() != 0 && num2 + 2 <= num1)
{
num1--;
num2++;
ac2.insert(*ac1.begin());
ac1.erase(ac1.begin());
other1.insert(*other2.begin());
other2.erase(other2.begin());
}
}
if (num1 == num2)
break;
if (aa2.size() != 0)
{
if (ac1.size() != 0)
{
num2++;
ac2.insert(*ac1.begin());
ac1.erase(ac1.begin());
aa1.insert(*aa2.begin());
aa2.erase(aa2.begin());
}
}
}
if (num1 != num2)
printf("-1");
else
{
for (auto it = aa2.begin(); it != aa2.end(); it++)
ans.push_back(*it);
for (auto it = cc2.begin(); it != cc2.end(); it++)
ans.push_back(*it);
for (auto it = ac2.begin(); it != ac2.end(); it++)
ans.push_back(*it);
for (auto it = other2.begin(); it != other2.end(); it++)
ans.push_back(*it);
for (int i = 0; i < ans.size(); i++)
printf("%d%c", ans[i], i == ans.size() - 1 ? '\n' : ' ');
}
}