codeforces 1321 C. Remove Adjacent(1600,贪心)

链接:https://codeforces.ml/problemset/problem/1321/C

题意:

对字符串S进行处理,删除其中的字符S[i],且S[i]满足S[i]-S[i-1]=1或S[i]-S[i+1]=1;最多可以删几次;

题解:

从最大的符合条件的S[i]开始处理;因为处理当前最大的不会影响后续操作;S的长度在100范围内,不会超时;

代码:

#include
using namespace std;
typedef long long ll;
int num[105] = { 0 };
int chuli(string s)
{
	int pos = 0;
	int ans = 0;
	int cnt = s.size();
	for (int i = 0; i < s.size(); i++)
	{
		if (s[i] != 'a' && (s[i] - s[max(i - 1, 0)] == 1 || s[i] - s[min(i + 1, cnt - 1)] == 1))
		{
			if (ans < s[i] - 'a')
			{
				ans = s[i] - 'a';
				pos = i + 1;
			}
		}
	}
	return pos;
}
int main()
{
	int n;
	cin >> n;
	string s;
	cin >> s;
	for (int i = 0; i < s.size(); i++)
	{
		num[i + 1] = s[i] - 'a' + 1;
	}
	int ans = 0;
	while (chuli(s))
	{
		num[chuli(s)] = 0;
		//cout << chuli(s) << " " << n << endl;
		string t;
		for (int i = 1; i <= n; i++)
		{
			if (num[i] != 0)
			{
				t = t + char(num[i] - 1 + 'a');
			}
		}
		n--;
		s = t;
		ans++;
		memset(num, 0, sizeof(num));
		for (int i = 0; i < s.size(); i++)
		{
			num[i + 1] = s[i] - 'a' + 1;
		}
	}
	
	cout << ans << endl;
	
	return 0;
}

你可能感兴趣的:(c++)