跳到正文

个人记录

SAM模板

_Snake_约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年5月20日
收录
2026年6月6日
更新
2026年11月11日
篇幅
约 3 分钟

版本

  1. v1当前
C++
struct SAM
{
	struct node
	{
		int link,len;
		map<int,int> ch;
	}t[MAXN<<1];
	int last,sz;
	void new_node(int length)
	{
		t[++sz].len=length;
		t[sz].link=-1;
		t[sz].ch.clear();
	}
	SAM()
	{
		last=0,sz=-1;
		new_node(0);
	}
	void insert(int c)
	{
		new_node(t[last].len+1);
		int p=last,cur=sz;
		while(p!=-1&&!t[p].ch[c])
		{
			t[p].ch[c]=cur;
			p=t[p].link;
		}
		if(p==-1)
		{
			t[cur].link=0;
		}
		else
		{
			int q=t[p].ch[c];
			if(t[q].len==t[p].len+1) 
			{
				t[cur].link=q;
			}
			else
			{
				new_node(t[p].len+1);
				int nq=sz;
				t[nq].ch=t[q].ch;
				t[nq].link=t[q].link;
				t[cur].link=t[q].link=nq;
				while(p!=-1&&t[p].ch[c]==q)
				{
					t[p].ch[c]=nq;
					p=t[p].link;
				}
			}
		}
		last=cur;
	}
}sam;
C++
struct SAM
{
	struct node
	{
		int link,len;
		int ch[26];
	}t[MAXN<<1];
	int last,sz;
	void new_node(int length)
	{
		t[++sz].len=length;
		t[sz].link=-1;
		memset(t[sz].ch,0,sizeof(t[sz].ch));
	}
	SAM()
	{
		last=0,sz=-1;
		new_node(0);
	}
	void insert(int c)
	{
		new_node(t[last].len+1);
		int p=last,cur=sz;
		while(p!=-1&&!t[p].ch[c])
		{
			t[p].ch[c]=cur;
			p=t[p].link;
		}
		if(p==-1)
		{
			t[cur].link=0;
		}
		else
		{
			int q=t[p].ch[c];
			if(t[q].len==t[p].len+1) 
			{
				t[cur].link=q;
			}
			else
			{
				new_node(t[p].len+1);
				int nq=sz;
				memcpy(t[nq].ch,t[q].ch,sizeof(t[q].ch));
				t[nq].link=t[q].link;
				t[cur].link=t[q].link=nq;
				while(p!=-1&&t[p].ch[c]==q)
				{
					t[p].ch[c]=nq;
					p=t[p].link;
				}
			}
		}
		last=cur;
		dp[cur]=1;
	}
}sam;
原文