1460. 我在哪?(二分,哈希)

https://www.acwing.com/problem/content/167/
n为100,因此对于我们这种枚举k值,枚举两个子串起点来判定是否存在相同子串的暴力做法O(N^4)是可以过的

#include<iostream>
#include<cstring>
using namespace std;
const int N = 110;
string a;
int n;
int main()
{
    cin >> n >> a;
    for(int k=1;k<=n;k++) //枚举连续查看多少次
    {
        bool flag=false;
        for(int i=0;i+k-1<n;i++)//枚举第一个子串起点
        {
            for(int j=i+1;j+k-1<n;j++)//枚举第二个子串起点
            {
                bool is_same=true;
                for(int u = 0; u < k;u++) 
                    if(a[i+u]!=a[j+u])
                    {
                        is_same=false;
                        break;
                    }
                if(is_same)//子串相同
                {
                    flag=true;
                    break;
                }
            }
            if(flag)//两个子串相等
                break;
        }
        if(!flag)
        {
            cout << k << endl;
            return 0;
        }
    }
    return 0;
}

对于优化,列出k值数轴的范围,可知k的值有一个分界点,使得分界点左边的k值不满足题意,而右边大的值满足题意,即左边的有相同子串,右边的没有
因此满足二段性,可以二分求出k的值
对于判断是否有相同的子串,可以用hash表判重,即用unordered_set或者map来判断即可

#include<iostream>
#include<cstring>
#include<unordered_set>
using namespace std;
const int N = 110;
string a;
int n;

bool check(int mid)
{
    unordered_set<string>Hash;
    for(int i=0;i+mid-1<n;i++)
    {
        string t = a.substr(i,mid);//取得子串
        if(Hash.count(t))return false;
        Hash.insert(t);
    }
    return true;
}
int main()
{
    cin >> n >> a;
    int l=1,r=n;
    while(l<r)
    {
        int mid = l+r>>1;
        if(check(mid))r=mid; //check成功就说明mid还在右边区间
        else l=mid+1;
    }
    cout << r << endl;
    return 0;
}

 

posted @ 2023-03-11 19:09  风乐  阅读(34)  评论(0)    收藏  举报