LCS spoj 1811

这题只要理解了sam中失配指针(即找到长度最大的和匹配串后缀相同的前缀)的性质和sam每个状态都表示某几个子串就可以做了。


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#include <cctype>
#include <utility>   
#include <map>
#include <string>  
#include <climits> 
#include <set>
#include <string>    
#include <sstream>
#include <utility>   
#include <ctime>

using std::priority_queue;
using std::vector;
using std::swap;
using std::stack;
using std::sort;
using std::max;
using std::min;
using std::pair;
using std::map;
using std::string;
using std::cin;
using std::cout;
using std::set;
using std::queue;
using std::string;
using std::istringstream;
using std::make_pair;
using std::getline;
using std::greater;
using std::endl;
using std::multimap;
using std::deque;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PAIR;
typedef multimap<int, int> MMAP;

const int MAXN(250010);
const int SIGMA_SIZE(26);
const int MAXM(110);
const int MAXE(300010);
const int MAXH(18);
const int INFI((INT_MAX-1) >> 1);
const int MOD(2520);
const ULL BASE(31);
const ULL LIM(1000000000000000ull);

struct SAM
{
	struct NODE
	{
		int len;
		NODE *f, *ch[SIGMA_SIZE];
	};
	NODE pool[MAXN << 1];
	NODE *root, *last;
	int size;
	void init()
	{
		last = root = pool;
		root->len = 0;
		root->f = 0;
		memset(root->ch, 0, sizeof(root->ch));
		size = 1;
	}
	NODE *newnode(int tl)
	{
		pool[size].len = tl;
		memset(pool[size].ch, 0, sizeof(pool[size].ch));
		return pool+size++;
	}
	void extend(int id)
	{
		NODE *p = last, *np = newnode(last->len+1);
		last = np; //别忘了
		while(p && p->ch[id] == 0)
			p->ch[id] = np, p = p->f;
		if(p == 0)
			np->f = root;
		else
		{
			NODE *q = p->ch[id];
			if(p->len+1 == q->len)
				np->f = q;
			else
			{
				NODE *nq = newnode(p->len+1);
				memcpy(nq->ch, q->ch, sizeof(nq->ch));
				nq->f = q->f;
				q->f = np->f = nq;
				while(p && p->ch[id] == q)
					p->ch[id] = nq, p = p->f;
			}
		}
	}
};

SAM sam;

char str[MAXN];

int main()
{
	while(~scanf("%s", str))
	{
		sam.init();
		for(char *tp = str; *tp; ++tp)
			sam.extend(*tp-'a');
		scanf("%s", str);
		int l = 0, ans = 0;
		SAM::NODE *p = sam.root;
		for(char *tp = str; *tp; ++tp)
		{
			int id = *tp-'a';
			if(p->ch[id] != 0)
			{
				p = p->ch[id];
				++l;
			}
			else
			{
				while(p && p->ch[id] == 0)
					p = p->f;
				if(!p)
				{
					p = sam.root;
					l = 0;
				}
				else
				{
					l = p->len+1;  //利用parent转移后,该状态表示的所有子串都是合法串,取最大的即可
					p = p->ch[id];
				}
			}
			ans = max(ans, l);
		}
		printf("%d\n", ans);
	}
	return 0;
}




你可能感兴趣的:(LCS spoj 1811)