紫书 习题 8-2 UVa 1610 (暴力出奇迹)

这道题我真的想的非常的复杂, 拿草稿纸一直在找规律,推公式, 然后总有一些特殊的情况。

然后就WA了N次。无奈之下看了别人的博客, 然后就惊了。直接暴力枚举两个相邻字符串

里面的所有可能就可以了……真的是暴力出奇迹!


#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;

const int MAXN = 1123;
string a[MAXN];

string work(string a, string b)
{
	int pos = 0;
	string s0 = "", t;
	while(1)
	{
		REP(i, 0, 26)
		{
			t = s0;
			t += i + 'A';
			if(a <= t && t < b) return t;
		}
		s0 += a[pos++];
	}
}

int main()
{
	int n;
	while(scanf("%d", &n) && n)
	{
		REP(i, 0, n) cin >> a[i];
		sort(a, a + n);
		int tmp = (n - 1) / 2;
		cout << work(a[tmp], a[tmp+1]) << endl;
	}
	return 0;
}