ac自动机

 

代码:

#include <bits/stdc++.h>
using namespace std;
char s[1000009];
#define maxn 500010
int c[maxn][26],val[maxn],fail[maxn],cnt;
void insert(char s[1000009])
{
  int len=strlen(s),now=0;
  for (int i=0;i<len;i++)
  {
    int v=s[i]-'a';
    if (!c[now][v]) c[now][v]=++cnt;
    now=c[now][v];
  }
  val[now]++;
}
queue<int> q; 
void build()
{
  for (int i=0;i<26;i++)
    if (c[0][i]) fail[c[0][i]]=0,q.push(c[0][i]);
  while (!q.empty())
  {
    int u=q.front(); q.pop();
    for (int i=0;i<26;i++)
      if (c[u][i])
      {
          fail[c[u][i]]=c[fail[u]][i];
          q.push(c[u][i]);
      }  else c[u][i]=c[fail[u]][i];
  }  
}
int query(char s[1000009])
{
  int len=strlen(s),now=0,ans=0;
  for (int i=0;i<len;i++)
  {
    now=c[now][s[i]-'a'];
    for (int t=now;t&&val[t]!=-1;t=fail[t])
    {
      ans+=val[t]; val[t]=-1;
    }
  } 
  return ans;
} 
int main()
{
  freopen("noip.in","r",stdin);
  freopen("noip.out","w",stdout);
  int n;
  cin>>n;
  for (int i=1;i<=n;i++)
  {
    cin>>s;
    insert(s);
  }
  build();
  cin>>s;
  cout<<query(s);
  return 0;
}

 

#include <bits/stdc++.h>
using namespace std;
char s[1000009];
#define maxn 500000
char jl[200][2000];
int c[maxn][26],val[maxn],fail[maxn],cnt,f[maxn];
vector<int>ff[maxn];
void insert(char s[1000009],int x)
{
  int len=strlen(s),now=0;
  for (int i=0;i<len;i++)
  {
    int v=s[i]-'a';
    if (!c[now][v]) c[now][v]=++cnt;
    now=c[now][v];
  }
  ff[now].push_back(x); val[now]++;
}
queue<int> q; 
void build()
{
  for (int i=0;i<26;i++)
    if (c[0][i]) fail[c[0][i]]=0,q.push(c[0][i]);
  while (!q.empty())
  {
    int u=q.front(); q.pop();
    for (int i=0;i<26;i++)
      if (c[u][i])
      {
          fail[c[u][i]]=c[fail[u]][i];
          q.push(c[u][i]);
      }  else c[u][i]=c[fail[u]][i];
  }  
}
int query(char s[1000009])
{
  int len=strlen(s),now=0,ans=0;
  for (int i=0;i<len;i++)
  {
    now=c[now][s[i]-'a'];
    for (int t=now;t&&val[t]!=-1;t=fail[t])
    {
      for (int i=val[t];i>=1;i--) f[ff[t][i-1]]++;
    }
  } 
  return ans;
} 
int main()
{
  freopen("noip.in","r",stdin);
  freopen("noip.out","w",stdout);
  int n;
  while (cin>>n&&n)
  {
    memset(c,0,sizeof(c));
    memset(f,0,sizeof(f));
    memset(val,0,sizeof(val));
    for (int i=0;i<=maxn-1;i++) ff[i].clear();
    for (int i=1;i<=n;i++)
    {
      cin>>s;
      for (int j=0;j<=1800;j++) jl[i][j]=s[j];
      insert(s,i);
    }
    build();
    cin>>s;
    query(s);
    int maxa=0;
    for (int i=1;i<=n;i++) maxa=max(maxa,f[i]);
    cout<<maxa<<endl;
    for (int i=1;i<=n;i++)
      if (f[i]==maxa)
        cout<<jl[i]<<endl;
  }
  return 0;
}

洛谷的两道模板题

ac自动机基本只要在模板上做修改就好了

posted @ 2018-02-18 20:23  尹吴潇  阅读(163)  评论(0编辑  收藏  举报