跳到正文

题解

AT_abc353_e solution

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

文章信息

发布
2024年5月18日
收录
2025年12月12日
更新
2026年11月5日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

Solution

看到字符串最大前缀,立马想到用字典树,于是问题就转化为如何在字典树上统计所有 sis_i 和 sjs_j 的最长前缀了。

考虑树形 dp。

对于字典树上的每个节点 uu,考虑计算 uu 对答案产生的贡献。我们可以发现,如果在以 uu 为根的子树中有两个节点有标记(即在字典树中标记为一个字符串),那么 uu 一定是这两个节点的前缀字符之一,所以会对答案产生 11 的贡献。再次扩展,如果以 uu 为根的子树中有 kk 个节点有标记,那么两两配对,总共会产生 k×(k−1)2\displaystyle \frac{k \times (k-1)}{2} 的贡献。于是,我们可以通过树形 dp 求出以 uu 为根的子树中的标记个数(包括节点 uu),再分别求其对答案的贡献并求和,即为答案。

Code

C++
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#define il inline
#define ll long long
using namespace std;
const int MAXN=3e5+5;
struct node
{
	int hv=0;
	int son[26]={};
};
const node emp;
int n;
vector <node> tr;
int cnt=0;
vector <ll> sum;
il int query(string s)
{
	int sz=s.size();
	int now=0;
	for(int i=0;i<sz;++i)
	{
		if(!tr[now].son[s[i]-'a'])
			return 0;
		now=tr[now].son[s[i]-'a'];
	}
	if(tr[now].hv)
		return now;
	return 0;
}
il void insert(string s)
{
	int sz=s.size();
	int _q=query(s);
	if(_q)
	{
		++tr[_q].hv;
		return;
	}
	int now=0;
	for(int i=0;i<sz;++i)
	{
		if(!tr[now].son[s[i]-'a'])
		{
			tr[now].son[s[i]-'a']=++cnt;
			tr.push_back(emp);
		}
		now=tr[now].son[s[i]-'a'];
	}
	tr[now].hv=1;
	return;
}
il ll dfs(int u)
{
	sum.emplace_back(1ll*tr[u].hv);
	int id=sum.size()-1;
	ll now;
	for(int i=0;i<26;++i)
	{
		if(tr[u].son[i])
		{
			now=dfs(tr[u].son[i]);
			sum[id]+=now;
		}
	}
	return sum[id];
}
int main()
{
	ios::sync_with_stdio(0);
	ios_base::sync_with_stdio(0);
	cin.tie(nullptr);
	cout.tie(nullptr);
	cin>>n;
	tr.push_back(emp);
	string s;
	for(int i=1;i<=n;++i)
	{
		cin>>s;
		insert(s);
	}
	dfs(0);
	ll ans=0;
	for(int i=1;i<sum.size();++i)
		ans+=max(0ll,sum[i]*(sum[i]-1)/2);
	cout<<ans;
	return 0;
}
原文