【CodeFores 798B】 Mike and strings(模擬+string)
Mike hasnstringss1, s2, ..., sneach consisting of lowercase English letters. In one move he can choose a stringsi, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".
Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
The first line contains integern(1 ≤ n ≤ 50) — the number of strings.
This is followed bynlines which contain a string each. Thei-th line corresponding to stringsi. Lengths of strings are equal. Lengths of each string is positive and don't exceed50.
OutputPrint the minimal number of moves Mike needs in order to make all the strings equal or print - 1
4 xzzwo zwoxz zzwox xzzwooutput
5input
2 molzv lzvmooutput
2input
3 kc kc kcoutput
0input
3 aa aa aboutput
-1Note
In the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz
題目大意:給n個字串,將第i個字串移動xi位,使得最終所有字串相等,求最小的移動步數和,若無法相等輸出-1
思路:n最大50個,列舉每一個字串作為基礎串,求得每種情況的移動步數和,取最小值。string find大發好,比賽時忘了用這個,結果沒懟出來。果然還是不太熟悉
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
int main()
{
int n,ans;
string s,t,p;
while(~scanf("%d",&n)){
vector<string>v;
ans=INF;
for (int i=0; i<n; i++){
cin>>s;
v.push_back(s);
}
for (int i=0; i<n; i++){
int sum=0;
t=v[i];
for (int j=0; j<n; j++){
if (i!=j){
p=v[j];
p+=p;
int k=p.find(t); //返回下標
if (k==-1){
sum=-1;
break;
}
sum+=k;
}
}
if (sum != -1) ans=min(ans,sum);
}
if (ans==INF) printf("-1\n");
else printf("%d\n",ans);
}
return 0;
}