【HDOJ】4162 Shape Number
循环串的最小表示法。
1 /* */ 2 #include <iostream> 3 #include <string> 4 #include <map> 5 #include <queue> 6 #include <set> 7 #include <stack> 8 #include <vector> 9 #include <deque> 10 #include <algorithm> 11 #include <cstdio> 12 #include <cmath> 13 #include <ctime> 14 #include <cstring> 15 #include <climits> 16 #include <cctype> 17 #include <cassert> 18 #include <functional> 19 #include <iterator> 20 #include <iomanip> 21 using namespace std; 22 //#pragma comment(linker,"/STACK:102400000,1024000") 23 24 #define sti set<int> 25 #define stpii set<pair<int, int> > 26 #define mpii map<int,int> 27 #define vi vector<int> 28 #define pii pair<int,int> 29 #define vpii vector<pair<int,int> > 30 #define rep(i, a, n) for (int i=a;i<n;++i) 31 #define per(i, a, n) for (int i=n-1;i>=a;--i) 32 #define clr clear 33 #define pb push_back 34 #define mp make_pair 35 #define fir first 36 #define sec second 37 #define all(x) (x).begin(),(x).end() 38 #define SZ(x) ((int)(x).size()) 39 #define lson l, mid, rt<<1 40 #define rson mid+1, r, rt<<1|1 41 42 const int maxl = 3e5+5; 43 char M[8][8]; 44 char s[maxl]; 45 char d[maxl]; 46 int len; 47 48 void init() { 49 rep(i, 0, 8) { 50 rep(j, 0, 8) { 51 M[i][j] = (j-i+8)%8 + '0'; 52 } 53 } 54 } 55 56 int minStr() { 57 int i, j, k; 58 int tmp; 59 60 i = 0; 61 j = 1; 62 k = 0; 63 while (i<len && j<len && k<len) { 64 tmp = d[(i+k)%len] - d[(j+k)%len]; 65 if (tmp == 0) { 66 ++k; 67 } else { 68 if (tmp < 0) 69 j += k+1; 70 else 71 i += k+1; 72 if (i == j) 73 ++j; 74 k = 0; 75 } 76 } 77 78 return i<j ? i:j; 79 } 80 81 int main() { 82 ios::sync_with_stdio(false); 83 #ifndef ONLINE_JUDGE 84 freopen("data.in", "r", stdin); 85 freopen("data.out", "w", stdout); 86 #endif 87 88 int k; 89 90 init(); 91 while (scanf("%s", s) != EOF) { 92 len = strlen(s); 93 s[len] = s[0]; 94 rep(i, 0, len) { 95 d[i] = M[s[i]-'0'][s[i+1]-'0']; 96 } 97 #ifndef ONLINE_JUDGE 98 d[len] = '\0'; 99 puts(d); 100 #endif 101 k = minStr(); 102 rep(i, 0, len) { 103 putchar(d[(k+i)%len]); 104 } 105 putchar('\n'); 106 } 107 108 #ifndef ONLINE_JUDGE 109 printf("time = %d.\n", (int)clock()); 110 #endif 111 112 return 0; 113 }