大前端

前端学习之家-大前端

学习笔记2

字典树

#include<bits/stdc++.h>
using namespace std;
const int N=100010;
int ne[N][26],idx,cnt[N];
void insert(string a)
{int p=0;
    for(int i=0;i<a.size();i++)
    {
        int u=a[i]-'a';
        if(!ne[p][u])ne[p][u]=++idx;
        p=ne[p][u];
    }
    cnt[p]++;
}
int ask(string a)
{int p=0;
    for(int i=0;i<a.size();i++)
    {
        int u=a[i]-'a';
        if(!ne[p][u])return 0;
        p=ne[p][u];
    }
    return cnt[p];
}

int main()
{int T;
cin>>T;
while(T--)
{string s;
char g;
cin>>g>>s;
if(g=='I')insert(s);
else cout<<ask(s)<<endl;
}
}

并查集

#include <bits/stdc++.h>
using namespace std;
int a[100010];
int root(int x)
{
if(x!=a[x])return  a[x]=root(a[x]);
return x;
}
void merge_root(int x,int y)
{int i=root(x),j=root(y);
if(i!=j)
    a[i]=root(a[j]);
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=0;i<m;i++)a[i]=i;
    char g;
    int x,y;
    while(m--)
    {
    cin>>g>>x>>y;
    if(g=='M')merge_root(x,y);
    else if(root(x)==root(y))cout<<"Yes"<<endl;
    else cout<<"No"<<endl;

    }
}

堆模拟

#include<bits/stdc++.h>
using namespace std;
int a[100010],cnt;
void down(int x)
{int m=x;
    if(2*x<=cnt&&a[x*2]<a[m])m=2*x;
    if(2*x+1<=cnt&&a[m]>a[x*2+1])m=2*x+1;
if(x!=m){
    swap(a[x],a[m]);
    down(m);
}
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)cin>>a[i];
    cnt=n;
    for(int i=n/2;i;i--)down(i);
    while(m--)
   { printf("%d ",a[1]);
       a[1]=a[cnt--];
       down(1);
   }
    cout<<endl;
}

hash

#include <bits/stdc++.h>
using namespace std;
const int N=100003;
int a[100010],e[100010],ne[100010],idx;
void insert(int x)
{
    int p=(x%N+N)%N;
    e[idx]=x;
    ne[idx]=a[p];
    a[p]=idx++;
}
bool query(int x)
{
    int p=(x%N+N)%N;
    int i=a[p];
    while(i!=-1)
    {
        if(e[i]==x)return 1;
        i=ne[i];
    }
    return 0;
}
int main()
{
    int T;
    cin>>T;
    memset(a,-1,sizeof a);
    while(T--)
    {
        char t;
        int x;
        cin>>t>>x;
        if(t=='I')insert(x);
        else if(query(x))puts("Yes");
        else puts("No");
    }
    return 0;
}

发表评论:

Copyright Your WebSite.Some Rights Reserved.