Codeforces 798 B. Mike and strings-String的find()函数

好久好久好久之前的一个题,今天翻cf,发现这个题没过,补一下。

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.

Examples
input
4
xzzwo
zwoxz
zzwox
xzzwo
output
5
input
2
molzv
lzvmo
output
2
input
3
kc
kc
kc
output
0
input
3
aa
aa
ab
output
-1
Note

In the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".

题意:给定的n个串,最少能移动几次使得这n个字符串相等。每次只能将字符串首位的移动到末尾。

想法:以某个串为标准, 改变其他的字符串,找出变化次数最小的。

这个题用string中的find()函数,简直不要太炫酷。

代码:

 #include<bits/stdc++.h>
using namespace std;
const int N=+;
string a[N]; int main(){
int n,i,j;
while(~scanf("%d",&n)){
for(i=;i<n;i++)
cin>>a[i];
int ans=0x3f3f3f,flag=;
for(i=;i<n;i++){
int sum=;
for(j=;j<n;j++){
string tmp=a[j]+a[j];
if(tmp.find(a[i])==string::npos)flag=;
else sum+=tmp.find(a[i]);
}
ans=min(ans,sum);
}
printf("%d\n",flag?-:ans);
}
return ;
}

string中的find()函数,查找字符串A是否包含子串B,不是用strA.find(strB) > 0而是strA.find(strB) != string:npos

返回的值是B在A中第一次出现的下标位置,如果没有查询到,则返回string::npos,如果返回npos就输出-1。

关于string中的find函数,看其他人写的吧。

传送门:1.哇哇哇2.呜呜呜3.汪汪汪4.喂喂喂

备忘一下。

上一篇:linux环境下,使用Navicat连接mysql时,提示本地IP无法连接虚拟环境下的mysql解决方案


下一篇:Python学习--Selenium模块