bzoj1398 Necklace
关于最小表示法的模板题。
最小表示法:把一个字符串表示为它的的所有循环同构字符串中的字典序最小者。
直接参见代码中的函数getmin()获取精髓
1 #include <cstdio> 2 #include <string> 3 #include <iostream> 4 5 using std::string; 6 using std::cin; 7 using std::cout; 8 using std::endl; 9 10 inline string getmin(string x) { 11 int n = x.size(); 12 string s = x + x; 13 int i = 0, j = 1; 14 while(i <= n && j <= n) { 15 int k = 0; 16 while(s[i + k] == s[j + k] && k < n) { 17 k++; 18 } 19 if(k == n + 1) { 20 return x; 21 } 22 if(s[i + k] < s[j + k]) { 23 j += k + 1; 24 if(j == i) { 25 j++; 26 } 27 } 28 else if(s[i + k] > s[j + k]) { 29 i += k + 1; 30 if(i == j) { 31 i++; 32 } 33 } 34 else { 35 printf("ERROR!\n"); 36 } 37 } 38 if(j > i) j = i; 39 string ans = ""; 40 for(i = 0; i < n; i++) { 41 ans += s[j + i]; 42 } 43 //cout << ans << endl; 44 return ans; 45 } 46 47 int main() { 48 string a, b; 49 cin >> a >> b; 50 //cout << a << endl << b << endl; 51 a = getmin(a); 52 b = getmin(b); 53 //cout << a << endl << b << endl; 54 if(a == b) { 55 printf("Yes\n"); 56 cout << a; 57 } 58 else { 59 printf("No"); 60 } 61 return 0; 62 }
一开始我把 j == i 写成了 j == 1 结果样例都过不了。。。