POJ3617-Best Cow Line 题解

题目直达
翻译自己找吧,简单说就是取字符串S的首或者尾放到字符串T中然后删掉首或者尾,直到S为空。问怎么样使T的字典序最小。

所以易知,只要判断S的首尾哪个小,直接放T中就可以了。但是如果像"ABCA"这样的呢,首和尾一样。那就判断下一位就好了。把一个题分步骤细化来达到全局最优解,这就是贪心。

#include 
#include 
#include 
using namespace std;
int N;
char S[2010];
void solve()
{
	int l = 0, r = N - 1;//代表数组S[l],S[l+1],...,S[r]也就是左右两端的下标
	while (l <= r)
	{
		bool left = false;//是左边的字符小吗?是该输出左边的字符吗?
		for (int i = 0; l + i <= r; i++)
		{
			if (S[l + i] < S[r - i])//首比尾小
			{
				left = true;
				break;
			}
			else if (S[l + i] > S[r - i])//尾比首小
			{
				left = false;
				break;
			}
			//那如果相等呢?相等就比较s[l+i+1]和b[r+i-1]比较下一位就行了
		}
		if (left) putchar(S[l++]);
		else putchar(S[r--]);
	}
	putchar('\n');
}
int main()
{
	cin >> N;
	cin >> S;
	solve();
	return 0;
}

你可能感兴趣的:(学习总结)