P4341 [BJWC2010] 外星联络

原题链接

题解

1.字符串集合map?但是无法做到字典序排序,所以是字典树
2.n<=3000,所以 \(O(n^2)\) 而且本题的特殊性,即每个子串都要放进去,所以要在 \(n^2\) 一边遍历一边放

code

#include<bits/stdc++.h>
using namespace std;
int cnt[9000005]={0};
int path[9000005][2]={0};
string s;
int num=0;

void dfs(int now)
{
    if(cnt[now]>1) cout<<cnt[now]<<endl;
    for(int i=0;i<=1;i++)
    {
        if(path[now][i])
        {
            dfs(path[now][i]);
        }
    }
}

int main()
{
    int n;
    cin>>n;
    cin>>s;

    for(int i=0;i<n;i++)
    {
        int now=0;
        for(int j=i;j<n;j++)
        {
            int to=s[j]-'0';
            if(!path[now][to]) path[now][to]=++num;
            now=path[now][to];
            cnt[now]++;
        }
    }

    dfs(0);
    return 0;
}

posted @ 2024-04-01 14:19  纯粹的  阅读(17)  评论(0)    收藏  举报