题目链接:http://codeforces.com/contest/777/problem/D
题意:n个字符串,保留前缀。希望保留尽可能多的字符,使得字典序单增。
把n个字符串翻转过来,相当于字典序递减。比较相邻两个字符串的字典序大小,用二分将当前字符串截至恰好比上一个字符串字典序小,且最长即可。
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 const int maxn = 500500; 5 int n; 6 string a[maxn], b[maxn]; 7 8 signed main() { 9 // freopen("in", "r", stdin); 10 while(~scanf("%d", &n)) { 11 for(int i = n; i >= 1; i--) cin >> a[i]; 12 b[1] = a[1]; 13 for(int i = 2; i <= n; i++) { 14 if(a[i] <= b[i-1]) { 15 b[i] = a[i]; 16 continue; 17 } 18 int lo = 0, hi = a[i].length(); 19 string ret; 20 while(lo <= hi) { 21 int mid = (lo + hi) >> 1; 22 if(a[i].substr(0, mid) <= b[i-1]) { 23 ret = a[i].substr(0, mid); 24 lo = mid + 1; 25 } 26 else hi = mid - 1; 27 } 28 b[i] = ret; 29 } 30 for(int i = n; i >= 1; i--) cout << b[i] << endl; 31 } 32 return 0; 33 }