标签:style blog color io os ar for sp div
给定长度为N的字符串S,构造长度为N的字符串T,起初T是空串,反复从S的头部或者尾部删除一个字符,加到T的尾部。目标是构造字典序尽可能小的T。尝试如下贪心算法:
考虑S头部和尾部字符相同的情况。有如下算法:
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 5 int N; 6 char S[2100]; 7 8 void solve() 9 { 10 int left = 0, right = N-1; 11 bool left_flag = false; 12 13 while (left <= right) 14 { 15 for (int i = 0; left+i <= right; i++) 16 { 17 if (S[left+i] < S[right-i]) 18 { 19 left_flag = true; 20 break; 21 } 22 else if (S[left+i] > S[right-i]) 23 { 24 left_flag = false; 25 break; 26 } 27 } 28 if (left_flag) putchar(S[left++]); 29 else putchar(S[right--]); 30 } 31 putchar(‘\n‘); 32 } 33 34 int main() 35 { 36 cin >> N; 37 for (int i = 0; i < N; i++) 38 cin >> S[i]; 39 40 solve(); 41 42 return 0; 43 }
标签:style blog color io os ar for sp div
原文地址:http://www.cnblogs.com/bournet/p/4002350.html