[uva] 146 - ID Codes
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=82
老套路了, dfs + 剪枝. 我超时了好几次啊 失误,失误,忘记剪枝了.
1 // 2 // main.cpp 3 // uva146 4 // 5 // Created by ello on 12/3/13. 6 // Copyright (c) 2013 NextLife. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <string> 11 #include <map> 12 #include <algorithm> 13 using namespace std; 14 15 string str; 16 string str2; 17 map<char, int> maps; 18 19 bool dfs(int cur) { 20 if (cur == str2.size()) { 21 if (str2 <= str) { 22 return false; 23 } 24 return true; 25 } 26 map<char, int>::iterator it; 27 for (it = maps.begin(); it != maps.end(); it++) { 28 long num = count(str2.begin(), str2.begin() + cur, (*it).first); 29 if ((*it).second > num) { 30 str2[cur] = (*it).first; 31 // cout<<cur<<','<<str2<<endl; 32 if (str2.substr(0, cur + 1) < str.substr(0, cur + 1) || !dfs(cur + 1)) { 33 continue; 34 } else { 35 return true; 36 } 37 } 38 } 39 return false; 40 } 41 42 int main(int argc, const char * argv[]) 43 { 44 while (getline(cin, str)) { 45 46 if (str == "#") { 47 break; 48 } 49 maps.clear(); 50 for (unsigned int i = 0; i < str.size(); ++i) { 51 maps[str[i]] += 1; 52 } 53 str2 = str; 54 bool flag = false; 55 for (unsigned int i = 1; i < str2.size(); ++i) { 56 if (str2[i] > str2[i - 1]) { 57 flag = true; 58 break; 59 } 60 } 61 if (flag && dfs(0)) { 62 cout<<str2<<endl; 63 } else { 64 cout<<"No Successor"<<endl; 65 } 66 } 67 return 0; 68 }