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?
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.
Print the minimal number of moves Mike needs in order to make all the strings equal or print - 1 if there is no solution.
4 xzzwo zwoxz zzwox xzzwo
5
2 molzv lzvmo
2
3 kc kc kc
0
3 aa aa ab
-1
In the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
题解:重点在于怎么在某个目标字符串中找到匹配串,因为有可更换的操作,需要统计操作步数最小数。
有两种方法,
第一种,写一个change函数,每次将首字母放到字符串末尾,统计多少次change操作之后可以和目标字符串匹配成功。
第二种,新开一个中间字符串量,设定为目标字符串+目标字符串,从而可以之间在中间量中之间使用string类内置的find函数/
此处采取第二种方法,代码如下:
//
// main.cpp
// B. Mike and strings
//
// Created by 徐智豪 on 2017/4/21.
// Copyright © 2017年 徐智豪. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
string s[100];
int n;
cin>>n;
for(int i=1;i<=n;i++)
cin>>s[i];
int minstep=10000,step;
int i,j;
for(i=1;i<=n;i++)
{
step=0;
for(j=1;j<=n;j++)
{
if(i!=j)
{
string temp=s[j]+s[j];
if((temp.find(s[i]))==string::npos)
{
return cout<<-1,0;
}
step+=temp.find(s[i]);
}
}
if(step<minstep)
minstep=step;
}
cout<<minstep<<endl;
return 0;
}