#410(div2)B. Mike and strings

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, 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?

Input

The first line contains integer n (1 ≤ n ≤ 50) — the number of strings.

This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.

Output

Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.

 1 #include<bits/stdc++.h>
 2 #define INF 1000000
 3 using namespace std;
 4 typedef long long ll;
 5 string s[102];
 6 ll n;
 7 int main(){
 8     scanf("%lld",&n);
 9     for(int i=0;i<n;i++){
10         cin>>s[i];
11     }
12     int ans=INF;
13     for(int i=0;i<n;i++){
14         int cnt=0;
15         for(int j=0;j<n;j++){
16             string temp=s[j]+s[j];
17             if(temp.find(s[i])==-1){
18                 cout<<-1<<endl;
19                 return 0;
20             }//不需判断是否相等,因为相等时,步数为0
21             cnt+=temp.find(s[i]); 
22         }    
23         ans=min(ans,cnt);
24     }
25     cout<<ans<<endl;
26     return 0;
27 } 
原文地址:https://www.cnblogs.com/elpsycongroo/p/6750526.html