題目鏈接:http://codeforces.com/contest/797/problem/C
題意:給個字符串,求字典序最小的出棧順序。
一開始想用優先隊列記錄全局最小的字符,然后每次入棧的時候檢查當前字符是不是最小的,如果是那么同時pop。這樣做的話,假如不是,那么棧里面的最小就找不到了。
所以重寫,直接維護一個數組sm[i]表示i之后的字符最小的是誰。從頭掃,每次都入棧。將棧里小于等于當前位置后綴的最小字符pop輸出就行了。
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 typedef long long LL; 5 const int maxn = 100100; 6 const int inf = 'z'+1; 7 int n; 8 char s[maxn], t[maxn], sm[maxn]; 9 priority_queue<char> pq; 10 11 int main() { 12 // freopen("in", "r", stdin); 13 while(~scanf("%s", &s)) { 14 n = strlen(s); 15 sm[n] = inf; 16 for(int i = n - 1; i >= 0; i--) { 17 sm[i] = min(sm[i+1], s[i]); 18 } 19 int j = 0; 20 for(int i = 0; i < n; i++) { 21 t[j++] = s[i]; 22 while(j && t[j-1] <= sm[i+1]) { 23 printf("%c", t[--j]); 24 } 25 } 26 printf("\n"); 27 } 28 return 0; 29 }
?