B. Take Your Places!(双指针,暴力)

B. Take Your Places!
原题地址:
题意
给你一串数,只能交换相邻的两个数,使得数列中不存在相邻的奇偶性相同的数,就是按照 奇数 偶数 奇数 偶数 … \dots … \dots 交替排列,求最小的交换次数。
思路:
记录奇数和偶数的个数,如果奇偶数的个数差大于1,必然不能奇数偶数交替排列,如果奇数比偶数大1,必然是 奇 偶 奇 偶 奇 …… 奇 这样排列,反之就是偶数打头。

遍历数组时用 cnto和 cnte记录一下当前有几个奇数偶数了,如果当前数i 是奇数,那它需要移动的距离是i-(2cnto-1) 因为第cnto个奇数所在的位置就是2cnto-1,i就是第cnto个奇数所在的位置。 偶数同理。

code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5+10;
int a[N];
int main()
{
    
    
	int t;
	cin>>t;
	while(t--)
	{
    
    
		int n;
		cin>>n;
		int anso=0,anse=0;
		int cnto=0,cnte=0;
		for(int i=1;i<=n;i++)
		{
    
    
			cin>>a[i];
			if(a[i]%2==0)
			{
    
    
				cnte++;
				anse+=abs(i-2*cnte+1);
			}
			else 
			{
    
    
				cnto++;
				anso+=abs(i-2*cnto+1);
			}
		}
		if(abs(cnto-cnte)>1)
		{
    
    
			cout<<-1<<endl;
		}
		else 
		{
    
    
			if(cnto>cnte)
			{
    
    
				cout<<anso<<endl;
			}
			else if(cnte>cnto)
			{
    
    
				cout<<anse<<endl;
			}
			else cout<<min(anse,anso)<<endl;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_43070117/article/details/120188174