codeforces刷题(1100):1907C_div3

发布时间 2023-12-24 23:54:46作者: Tom-catlll

C、Removal of Unattractive Pairs

跳转原题点击此:[该题地址](Problem - 1907C - Codeforces)

1、题目大意

  给定一个字符串,可以删除相邻的两个不相等的字符。问你删除后能得到最小的字符串长度为多少。

2、题目解析

  因为只要两个不相等的字符相邻就能消除,所以只需要找到数量最多的字符,只要它的数量比其它字符数量和多,那么剩下的字符一定是数量最多的字符;

如果其它字符数量和多,只需要判断字符串长度是不是偶数,如果是,那么就一定能全部消除,否则,一定剩下一个字符。

#include<bits/stdc++.h>

using namespace std;

const int N = 2e5 + 10;

int t;
int n;
string s;
map<char, int>mp;

void solve()
{
	s.clear();
	mp.clear();
	
	cin >> n >> s;
	int maxx = 0;
	for(auto tmp : s)
	{
		mp[tmp]++;  // 记录字符的数量
		maxx = max(maxx, mp[tmp]);
	}
	
	int half = n / 2;
	if(maxx >= half)
		cout << abs(maxx - (n - maxx)) << endl;
		
	else
		if(n & 1)  // 判断奇偶
			cout << 1 << endl;
		else
			cout << 0 << endl;
}

int main()
{
	cin >> t;
	while (t--)
	{
		solve();
	}

	return 0;
}