CodeForces - 798B:Mike and strings

CodeForces - 798B: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?

输入

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.

提示

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

输入样例1

4
xzzwo
zwoxz
zzwox
xzzwo

输出样例1

5

输入样例2

2
molzv
lzvmo

输出样例2

2

输入样例3

3
kc
kc
kc

输出样例3

0

输入样例4

3
aa
aa
ab

输出样例4

-1

解题思路

参考代码

#include<stdio.h>
#include<string.h>
int main()
{
    int n;//字符串数 
    scanf("%d",&n);

    char str[n][55];
    int i,j,k,c;

    for(i=0;i<n;i++)
    scanf("%s",str[i]);//读入字符串

    int len=strlen(str[0]);//获取字符串长度 
    int min;//最少移动次数 
    int judge=1;//用于判断能否满足条件 

    for(i=0;i<n;i++)//以str[i]作为模版 
    {
        int sum=0;//每个模版下总的移动次数 
        for(j=0;j<n;j++)
        {
            if(i==j)continue;
            int count=0;//剩余的字符串中,每个对模版所需的移动次数 
            char temp[len+1];//为了不改变原字符串,设置一个临时数组 
            strcpy(temp,str[j]);
            temp[len]='\0';
            for(k=0;k<len;k++)
            {
                if(str[i][k]!=temp[k])
                {
                    count++;
                    //模拟操作:将第一位移动到最后一位 
                    temp[len]=temp[0];
                    for(c=0;c<len+1;c++)
                    temp[c]=temp[c+1];
                    temp[len]='\0';
                    k=-1;//从头开始再检查 
                } 
                if(count==len)//如果移动了这么多次,两个字符串还是不相等,就判断不满足 
                {
                    judge=0;
                    goto part1;
                }
            }
            sum+=count;
        }
        if(i==0)min=sum;
        else if(sum<min)min=sum;
    }

    part1:
        if(judge==0)
        printf("-1\n");
        else printf("%d\n",min);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/wingrez/article/details/80474707