Necklace Decomposition Necklace Decomposition
#include <bits/stdc++.h>
using namespace std;
bool necklace(string s) {
string x;
int n = s.size();
for(int i = 1; i < n; i++) {
x = s.substr(i, n-i) + s.substr(0, i);
if(x < s)
return false;
}
return true;
}
int main() {
freopen("data.in", "r", stdin);
int T, N;
string s, x;
scanf("%d", &T);
for(int i = 0; i < T; i++) {
cin >> s;
N = s.size();
for(int j = 0; j < N; ) {//从j开始切,贪心法
for(int k = N - j; k >= 0; k--) {//k为长度,从最长的开始试一试
x = s.substr(j, k);//j开始取k长度子串
if(necklace(x)) {
cout<<"("<<x<<")";
j = j + k;
break;
}
}
}
cout<<endl;
}
return 0;
}