Codeforces Round 915 (Div. 2) C题样例解释

Problem - C - Codeforces

看懂这个样例很重要:

15

czddeneeeemigec

Codeforces Round 915 (Div. 2) C题样例解释_第1张图片

AC代码:

#include
using namespace std;
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long 
const int MAX = 2e5 + 5;
int arr[MAX] = { 0 };
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int t;
	cin >> t;
	while (t--)
	{
		memset(arr, 0, sizeof arr);
		int n;
		cin >> n;
		string str;
		cin >> str;
		string msubstr;

		//找到最大子序列 —— 遍历n^2超时
		unordered_maphash;
		for (char x : str)
			hash[x]++;
		for (int i = 0; i < str.size(); i++)
		{
			int j = str[i] + 1;
			for (; j <= 'z'; j++)
			{
				if (hash[j] != 0)
					break;
			}
			hash[str[i]]--;
			if (j <= 'z')continue;
			arr[i] = 1;//标记为子串
			msubstr += str[i];
		}
		//cout << "#### " << msubstr << endl;


		//其实就是翻转啊
		reverse(msubstr.begin(), msubstr.end());
		auto it = msubstr.begin();
		//改原串吧	
		for (int i = 0; i < str.size(); i++)
		{
			if (arr[i] == 1)
			{
				str[i] = *it;
				it++;
			}
		}
		//移动过才用比
		int i = 1;
		for (; i < str.size(); i++)
		{
			if (str[i] < str[i - 1])
				break;
		}
		if (i != str.size())
			cout << -1 << endl;
		else
		{
			/*if (msubstr[0] == msubstr.back())
				cout << 0 << endl;
			else*/
			//bdcdcb
			int s = 1;
			for (int j = msubstr.size() - 2; j >= 0; j--)
			{
				if (msubstr[j] == msubstr.back())
					s++;
				else
					break;
			}
			cout << msubstr.size() - s << endl;
		}
	}
	return 0;
}

你可能感兴趣的:(算法,c语言,开发语言,算法)