CodeForces - 798B Mike and strings 【思维】

Description(下方有汉语题意)

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".

题意

小A有n个字符串s1,s2,...,sn,每个字符串由小写英文字母组成。

在一次操作中,他可以选择字符串si,擦除第一个字符并将其附加到字符串的末尾。

例如,如果他有字符串“coolsmalla”,他可以在一次操作中将其转换为字符串“oolsmallac”。

现在小A想知道,要想使n个字符串全部相同,他至少要做几次这样的操作。

输入:
第一行一个数n(1<=n<=50),表示字符串的个数
随后n行,每行给出一个字符串,字符串长度不会超过50

输出:
输出一个数表示需要的最少操作数,如果不能使得所有字符串相同,输出-1

解题思路

把两个字符次序不同的字符串的字符次序变得相同,可以以其中一个为准,把另一个变成它的样子,也可以都变成第三态,但是是把操作限定在了“擦除第一个字符并将其附加到字符串的末尾 ”,那么操作此处最少的方法必然是第一种。(模拟下就看出来了)。

现在有n个串,我们先确定一个串(从1号串到n号串依次尝试),把另外n-1个串变成他的样子。操作次数最少的那个就是答案。

用到了 string 的 find()函数:假如我们有连个string串a,b。a.find(b)就是在a中第一次找到b时,首字符的位置。找不到返回string::npos。我们现在假设a串由两个‘abbba’串拼接起来,即a为'abbbaabbba',b串为bbbaa,那么我们‘abbba’变成b串‘bbbaa’,只需要把第一个字符a放到最后即可。即只需要操作一次。这里你会惊奇的发现a.find(b)的返回值正是1。

AC代码

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
string a[55];
string b[55];
int main()
{
	int n;
	cin >> n;
	for(int i=1;i<=n;i++) {
		cin >> a[i];
		b[i] = a[i]+a[i];
	}
	
	bool flag = false;
	int minn=0x3f3f3f3f,sum;
	for(int i=1;i<=n;i++) {
		sum = 0;
		for(int j=1;j<=n;j++) {
			if(b[j].find(a[i]) == string::npos) {
				flag = true;
				cout << "-1" << endl;
				break;
			}
			else
				sum += b[j].find(a[i]);
		}
		if( flag)
			break;
		minn = min(minn,sum);
	}
	if(!flag)
		cout << minn << endl;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值