A - Mike and strings
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?
**问题分析:**题意是说给定几个字符串然后问最少移动需要几步才能把这几个字符串移为一样的;(移动规则是把首字母移动到尾部)
**解题思路:**首先需要知道#include带的函数 find();
string1.find(string2)
这个函数意思是在string1中查询是否存在string2若存在返回string2在string1中首字符的地址下标 若查询不到则返回 string::npos ;这个npos是一个-1或者很大的数。
其次就是本题一个巧妙之处 把移动的函数复制一遍 作为string1然后在string1中查询string2(模板字符串)
例如:4
xzzwo
zwoxz
zzwox
xzzwo
string1:(xzzwoxzzwo) string2 :zwoxz(模板字符串) 明显看出stringg2出现在 3 则需要移动三步 此为本题主要解题关键
实现代码:
#include<iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include<string>
using namespace std;
const int N = 100 + 10;
string a[N];
int main()
{
int n;
while(scanf("%d",&n) == 1)//若i=1则继续循环否则退出
{
for(int i = 0; i < n; i++)
cin>>a[i];
int ans = 0x3f3f3f, flag = 0; //ans是一个很大的数
for(int i = 0; i < n; i++)//以每个字符串目标模板 看需要移动几步最后找出最少步数的模板
{
int sum = 0;
for(int j = 0; j < n; j++)
{
string tmp = a[j] + a[j];//将当前找的这个字符串复制两遍在这个复制两遍的字符串里找a[i]出现的位置返回的坐标就是需要移动的步数
if(tmp.find(a[i]) == string::npos) flag = 1;//string自带的find()string1中查找string2,
else
{
sum += tmp.find(a[i]) ;//string1.find(string2)将返回string2第一次在string1中出现的位置
} ;
}
ans = min(ans, sum);
}
printf("%d\n", flag ? -1 : ans); //就是if(flag)cout<<-1 else cout<<ans;
}
}
分享如上,如有问题望读者指出,若有不解可留言作者一定给予解惑。