cf1556B B. Take Your Places!
题意:
有n个数,你可以将相邻两个数交换,使得奇偶性一样的数不相邻。问最少操作步数
题解:
最终排列无非是:奇,偶,奇…或者偶,奇,偶…
如果奇数>偶数,我们就按照第一个排,如果偶数>奇数,我们就按照第二个排。如果两者相等,两种排列都测一遍,取较小值
代码:
// Problem: B. Take Your Places!
// Contest: Codeforces - Deltix Round, Summer 2021 (open for everyone, rated, Div. 1 + Div. 2)
// URL: https://codeforces.com/contest/1556/problem/B
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// Data:2021-08-31 23:46:12
// By Jozky#include <bits/stdc++.h>
#include <unordered_map>
#define debug(a, b) printf("%s = %d\n", a, b);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
clock_t startTime, endTime;
//Fe~Jozky
const ll INF_ll= 1e18;
const int INF_int= 0x3f3f3f3f;
void read(){};
template <typename _Tp, typename... _Tps> void read(_Tp& x, _Tps&... Ar)
{x= 0;char c= getchar();bool flag= 0;while (c < '0' || c > '9')flag|= (c == '-'), c= getchar();while (c >= '0' && c <= '9')x= (x << 3) + (x << 1) + (c ^ 48), c= getchar();if (flag)x= -x;read(Ar...);
}
template <typename T> inline void write(T x)
{if (x < 0) {x= ~(x - 1);putchar('-');}if (x > 9)write(x / 10);putchar(x % 10 + '0');
}
void rd_test()
{
#ifdef LOCALstartTime= clock();freopen("in.txt", "r", stdin);
#endif
}
void Time_test()
{
#ifdef LOCALendTime= clock();printf("\nRun Time:%lfs\n", (double)(endTime - startTime) / CLOCKS_PER_SEC);
#endif
}
const int maxn= 1e5 + 9;
int a[maxn];
int b[maxn];
int main()
{//rd_test();int t;read(t);while (t--) {int n;read(n);vector<int> q1; //奇数vector<int> q2; //偶数for (int i= 0; i < n; i++) {read(a[i]);if (a[i] % 2 == 1) //奇数q1.push_back(i);elseq2.push_back(i);}if (n == 1)printf("0\n");else if (abs((int)q1.size() - (int)q2.size()) > 1)printf("-1\n");else if ((int)q1.size() > (int)q2.size()) {int pos= 0;ll sum= 0;for (int i= 0; i < q1.size(); i++) {sum+= abs(q1[i] - pos);pos+= 2;}printf("%lld\n", sum);}else if ((int)q1.size() < (int)q2.size()) {int pos= 0;ll sum= 0;for (int i= 0; i < q2.size(); i++) {sum+= abs(q2[i] - pos);pos+= 2;}printf("%lld\n", sum);}else if ((int)q1.size() == (int)q2.size()) {int pos= 0;ll sum= 0;for (int i= 0; i < q1.size(); i++) {sum+= abs(q1[i] - pos);pos+= 2;}pos= 0;ll sum2= 0;for (int i= 0; i < q2.size(); i++) {sum2+= abs(q2[i] - pos);pos+= 2;}printf("%lld\n", min(sum, sum2));}}return 0;//Time_test();
}