CF--EDU--142

D. Fixed Prefix Permutations

思路

字典树的应用
因为要对前面已经有过的信息进行筛选,可以用字典树来进行维护

思路

#include <bits/stdc++.h>
using namespace std;
using pii=pair<int,int>;
using pdd=pair<double,double>;
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define TT int _=read();while(_--)
#define int long long
using ll=long long;
const ll inf=1e18;
//#define double long double
#define endl '\n'
const int M=5e4+5;

inline int read(){
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    return x*f;
}

inline void print(int x) {
    if(x<0){putchar('-');x=-x;}
    if(x/10)print(x/10);
    putchar(x%10+'0');
}

//对前面的信息进行更新合并,经典的字典树呀
int n,m;
int a[M][11],b[M][11];
int ch[M*10][11],tot;

void insert(int c[]) {
    int p=0;
    for(int i=1;i<=m;i++) {
        if(!ch[p][c[i]])ch[p][c[i]]=++tot;
        p=ch[p][c[i]];
    }
}

int solve(int c[]) {
    int p=0;
    for(int i=1;i<=m;i++) {
        if(ch[p][c[i]]==0)return i-1;
        p=ch[p][c[i]];
    }
    return m;
}

signed main() {
    TT {
        for(int i=0;i<=tot;i++)
            for(int j=1;j<=10;j++)ch[i][j]=0;
        tot=0;
        n=read(),m=read();
        for(int i=1;i<=n;i++) {
            for(int j=1;j<=m;j++) {
                a[i][j]=read();
                b[i][a[i][j]]=j;//这个位置应该是什么数,才可以进行匹配
            }
            insert(b[i]);
        }
        for(int i=1;i<=n;i++)
            cout<<solve(a[i])<<' ';
        cout<<'\n';
    }
    return 0;
}
posted @ 2023-02-14 17:02  basicecho  阅读(27)  评论(0)    收藏  举报