http://www.elijahqi.win/archives/2972
建出广义后缀自动机 根据题意要求就是用最少的人数覆盖广义后缀自动机 所以拆点 每个点下界为1 上界也是1 注意源点向每个节点连1 的边 每条转移的边都是流量为1的边 直接跑最小流即可 最小流就是首先不加汇到源的边 先跑 将下界流量调整对 然后再重新添加t-s的边 再最大流 最后就是s->t的边权的最小值了
#include<map>
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 22000
#define inf 0x3f3f3f3f
#define rg register
#define it map<int,int>::iterator
using namespace std;
inline char gc(){
static char now[1<<16],*S,*T;
if (T==S){T=(S=now)+fread(now,1,1<<16,stdin);if(T==S) return EOF;}
return *S++;
}
inline int read(){
int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=gc();}
while(ch<='9'&&ch>='0') x=(x<<3)+(x<<1)+ch-'0',ch=gc();
return x*f;
}
struct node{
int y,next,z,x;
}data[N*5];
map<int,int> ch[N];
int fa[N],last=1,cnt=1,root=1,len[N],n,k;
inline void insert1(int x){
int p=last;
if (ch[p][x]){
int q=ch[p][x];
if (len[p]+1==len[q]) last=q;else{
int nq=++cnt;ch[nq]=ch[q];fa[nq]=fa[q];fa[q]=nq;len[nq]=len[p]+1;
for(;p&&ch[p][x]==q;p=fa[p]) ch[p][x]=nq;last=nq;
}
}else{
int np=++cnt;len[np]=len[p]+1;fa[np]=p;
for (;p&&!ch[p][x];p=fa[p]) ch[p][x]=np;
if (!p) fa[np]=root;else{
int q=ch[p][x];if (len[p]+1==len[q]) fa[np]=q;else{
int nq=++cnt;ch[nq]=ch[q];fa[nq]=fa[q];fa[q]=fa[np]=nq;
len[nq]=len[p]+1;for (;p&&ch[p][x]==q;p=fa[p]) ch[p][x]=nq;
}
}last=np;
}
}
int level[N],h[N],cur[N],in[N],num=1,T,m;
inline void insert1(int x,int y,int z){
data[++num].y=y;data[num].next=h[x];data[num].z=z;h[x]=num;data[num].x=x;
data[++num].y=x;data[num].next=h[y];data[num].z=0;h[y]=num;data[num].x=y;
}
inline bool bfs(){
memset(level,0,sizeof(level));queue<int> q;level[0]=1;q.push(0);
while(!q.empty()){
int x=q.front();q.pop();
for (int i=h[x];i;i=data[i].next){
int y=data[i].y,z=data[i].z;
if (level[y]||!z) continue;level[y]=level[x]+1;if (y==T) return 1;q.push(y);
}
}return 0;
}
inline int dfs(int x,int s){
if (x==T) return s;int ss=s;
for (int &i=cur[x];i;i=data[i].next){
int y=data[i].y,z=data[i].z;
if (level[x]+1==level[y]&&z){
int xx=dfs(y,min(z,s));if (!xx) level[y]=0;
s-=xx;data[i].z-=xx;data[i^1].z+=xx;if (!s) return ss;
}
}return ss-s;
}
int main(){
freopen("friend.in","r",stdin);
k=read();n=read();
for (rg int i=1;i<=n;++i,last=root)
for (rg int j=read();j;--j) insert1(read());
for (rg int i=2;i<=cnt;++i) --in[i],++in[i+cnt];int s=cnt*2+1;
for (it i=ch[1].begin();i!=ch[1].end();++i) insert1(i->second+cnt,1,1);
for (rg int i=2;i<=cnt;++i){
insert1(s,i,1);
for (it j=ch[i].begin();j!=ch[i].end();++j) insert1(j->second+cnt,i,1);
}T=s+1;int sum=0,ans=0;
for (rg int i=1;i<=s;++i) if(in[i]<0) insert1(i,T,-in[i]);else if (in[i]>0) insert1(0,i,in[i]),sum+=in[i];
// for (int i=2;i<=num;++i) printf("%d %d %d\n",data[i].x,data[i].y,data[i].z);
while(bfs()) memcpy(cur,h,sizeof(h)),ans+=dfs(0,inf);
insert1(1,s,inf);while(bfs()) memcpy(cur,h,sizeof(h)),ans+=dfs(0,inf);
if (ans!=sum) {puts("0");return 0;}printf("%d\n",data[num].z);
return 0;
}