UVA 146 - ID Codes
我写了两个版本。都AC了哟亲。
第一个是用STL里面的next_permutation,非常简单。
第二个是不用next_permutation,算法很简单。
如果这个ID存在successor的话,至少存在一个i,使得code[i] < code[i+1] 且 code[j] > code[j+1] for j in [i+1, size-1]。如果不存在这样的i,那么就是没有successor。

1 #include <iostream> 2 #include <algorithm> 3 #include <string> 4 using namespace std; 5 6 int main(){ 7 char code[50]; 8 while (cin >> code && code[0] != '#'){ 9 int size = char_traits<char>::length(code); 10 bool next = next_permutation(code, code+size); 11 if (next) 12 cout << code << endl; 13 else 14 cout << "No Successor" << endl; 15 } 16 17 return 0; 18 }

1 #include <iostream> 2 #include <string> 3 #include <algorithm> 4 using namespace std; 5 6 int cmp(const void* _a, const void* _b){ 7 return ( *(char*)_a - *(char*)_b ); 8 } 9 10 bool next_code(char code[]) { 11 int size = char_traits<char>::length(code), pos = size-2; 12 13 while (pos >= 0){ 14 if (code[pos] < code [pos+1]) 15 break; 16 pos--; 17 } 18 if (pos == -1) 19 return false; 20 int length = size - pos; 21 char head = code[pos]; 22 23 qsort(code+pos, length, sizeof(char), cmp); 24 int index = pos; 25 while (index < size){ 26 if (code[index] > head) 27 break; 28 index++; 29 } 30 code[pos] = code[index]; 31 code[index] = head; 32 qsort(code+pos+1, length-1, sizeof(char), cmp); 33 return true; 34 } 35 36 int main(){ 37 char code[50]; 38 while (cin >> code && code[0] != '#'){ 39 bool next = next_code(code); 40 if (next) 41 cout << code << endl; 42 else 43 cout << "No Successor" << endl; 44 } 45 }
这里的东西都是自娱自乐的.我只是抱着构思算法的心态去做UVA的题.
我所有的code都不可能AC的.因为我就没想着让它能AC.