排位赛1-I Where Am I?
题目
Farmer John has gone out for a walk down the road and thinks he may now be lost! Along the road there are N farms (1≤N≤100) in a row. Farms unfortunately do not have house numbers, making it hard for Farmer John to figure out his location along the road. However, each farm does have a colorful mailbox along the side of the road, so Farmer John hopes that if he looks at the colors of the mailboxes nearest to him, he can uniquely determine where he is.
Each mailbox color is specified by a letter in the range A…Z, so the sequence of N mailboxes down the road can be represented by a string of length N containing letters in the range A…Z. Some mailboxes may have the same colors as other mailboxes. Farmer John wants to know what is the smallest value of K such that if he looks at any sequence of K consecutive mailboxes, he can uniquely determine the location of that sequence along the road.
For example, suppose the sequence of mailboxes along the road is ‘ABCDABC’. Farmer John cannot set K=3, since if he sees ‘ABC’, there are two possible locations along the road where this consecutive set of colors might be. The smallest value of K that works is K=4, since if he looks at any consecutive set of 4 mailboxes, this sequence of colors uniquely determines his position along the road.
题意
FJ迷路了,他现在要确定他的位置,沿路有n个农场,每个农场有一个字母来表示,现在FJ需要找出最短的连续的农场数K,使得这n个农场中没有重复的长度为K的连续序列。
解法
如果长度为a的连续序列有重复那么比a小的也肯定有,如果长度为a的连续序列没有重复那么比a大的也没有,所以我们可以用二分答案来找K。
代码:
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
using namespace std;
int n;
string st;
bool judge(int x)
{
bool flag=true;
for (int i=1;i<n-x+1;i++)
{
for (int j=0;j<i;j++)
{
bool temp=true;
for (int k=0;k<x;k++)
{
if (st[i+k]!=st[j+k]) temp=false;
}
if (temp) flag=false;
}
}
return flag;
}
int main()
{
scanf("%d",&n);
cin>>st;
int l=1,r=n;
while (l+1<r)
{
int mid=(l+r)/2;
if (judge(mid)) r=mid; else l=mid;
}
printf("%d",r);
return 0;
}