题目链接: https://ac.nowcoder.com/acm/contest/15329/I.
题目描述
There are three horizontal wheels of letters stacked one on top of the other, all with the same number of columns. All wheels have one letter, either ‘A’, ‘B’ or ‘C’, in each of its columns on the edge of the wheel. You may rotate the wheels to adjust the positions of the letters. In a single rotation, you can rotate any single wheel to the right or to the left by one column. The wheels are round, of course, so the first column and last column are adjacent.
You would like to determine whether it is possible to rotate the wheels so that every column has three distinct letters across the three wheels, and if so, determine the minimum number of rotations required.
输入描述:
The input has exactly three lines. Each line has a string s (2 ≤ |s| ≤ 5 · 103) consisting only ofupper-case letters ‘A’, ‘B’ or ‘C’, describing the letters of one wheel in their initial positions. Allthree strings will be of the same length.
输出描述:
Output a single integer, which is the minimum number of rotations required, or −1 if it isn’tpossible.
示例1
输入
ABC
ABC
ABC
输出
2
示例2
输入
ABBBAAAA
BBBCCCBB
CCCCAAAC
输出
3
看注释:
#include<bits/stdc++.h>
using namespace std;
string s0,s1,s2;
int flag[3][5005];
int cnt=0x3f3f3f3f;
/*
基本是抄的网上题解的答案
这题正常思路应该是遍历每种可能出现的状态,
所有可能的状态有n2 判断两串是否相等是n 总体为n3超时
但是用n2的预处理可以计算出每两串之间是否相等
之后用n2的遍历即可
对于判断三者之间的关系,预处理两两的状态优化
*/
void ini(int len){
memset(flag,1,sizeof(flag));
for(int i=0;i<len;i++)
for(int j=0;j<len;j++)
{
if(s0[j]==s1[(i+j)%len])
flag[1][i]=0;//前两个字符串偏移量为i的时候是否相等 (1则表示完全不等
if(s0[j]==s2[(i+j)%len])
flag[2][i]=0;//一三个字符串偏移量为i的时候是否相等 (1则表示完全不等
if(s1[j]==s2[(i+j)%len])
flag[0][i]=0;//二三个字符串偏移量为i的时候是否相等 (1
}
}
int main()
{
cin>>s0>>s1>>s2;
int len=s1.size();
ini(len);
int mi,mj,tmp;
for(int i=0;i<len;i++)
for(int j=0;j<len;j++)
if(flag[0][(j+len-i)%len]&&flag[1][i]&&flag[2][j]){//第二串向前i 第三串向前j
//分几种情况1两次移动都是小于一半,直接取大的(第一串反向)
//2两次移动都是大于一半,直接取len-i和len-j的大的(第一串正向)
//3两次移动一次大于,一次小于此时移动第一串或者移动下两串反向之和的都有可能
// if(i*2>len&&j*2>len){
cnt=min(cnt,max(len-i,len-j));
// continue;
// }
//这里不能用if 理由是不能保证j一定大于i (上面三种情况基于同向,实际反向也有可能)
mi=min(i,len-i);
mj=min(j,len-j);
cnt=min(cnt,min(max(i,j),mi+mj));
}
if(cnt==0x3f3f3f3f)
cout<<-1<<endl;
else
cout<<cnt<<endl;
return 0;
}