You are given a tree T consisting of n vertices and n−1 edges. Each edge of the tree is associated
with a lowercase English letter ci
.
You are given a string s consisting of lowercase English letters. Your task is to find a simple path
in the tree such that the string formed by concatenation of letters associated with edges of this
path contains string s as a subsequence, or determine that there exists no such simple path.
Input
The first line of input contains two positive integers n and m (2 ≤ n ≤ 5 · 105
, 1 ≤ m ≤ n − 1),
the number of vertices in the tree and the length of the string s.
The following n − 1 lines contain triples ui
, vi
, ci (1 ≤ ui
, vi ≤ n, ui ̸= vi
, ci
is a lowercase English
letter), denoting an edge (ui
, vi) associated with letter ci
.
The last line contains a string s (|s| = m) consisting of lowercase English letters.
Output
If the desired path exists, output its endpoints a and b. Otherwise, output “-1 -1”. If there are
several possible answers, you are allowed to output any of them.
Example
input
9 3
1 2 a
2 3 b
2 4 a
4 5 b
4 6 c
6 7 d
6 8 a
8 9 b
acb
output
8 3
题意:
给你n-1行(wa在这里两次)每行包含三个数:两条相连的点和这个边的权值(一个字符),最后给你一个长为m的字符串,让你求任意两个端点使得这两个端点的路径上的字符串包含这个字符8 3 和3 8是不一样的。
题解:
先建树,接下来从1开始dfs,找到叶子节点回溯的时候看是否首尾的长度已经有m了,然后再把儿子的值更新给父亲。
#include<bits/stdc++.h>
using namespace std;
#define pa pair<int,int>
#define mp(a,b) make_pair(a,b)
const int N=5e5+5;
struct node
{
int to,next,val;
}e[N<<1];
int head[N],cnt,n,m;
char ss[N];
pa sta[N],en[N],ans;
void add(int x,int y,int w)
{
e[cnt].to=y;
e[cnt].next=head[x];
e[cnt].val=w;
head[x]=cnt++;
}
char s[2];
void dfs(int son,int fa)
{
sta[son]=en[son]=mp(0,son);
//if(ans.first!=-1&&ans.second!=-1)
//return ;
for(int i=head[son];~i;i=e[i].next)
{
int ne=e[i].to;
if(ne==fa)
continue;
dfs(ne,son);
if(sta[ne].first<m&&e[i].val==ss[sta[ne].first])
sta[ne].first++;
if(en[ne].first<m&&e[i].val==ss[m-1-en[ne].first])
en[ne].first++;
if(sta[son].first+en[ne].first>=m)
ans=mp(sta[son].second,en[ne].second);
if(sta[ne].first+en[son].first>=m)
ans=mp(sta[ne].second,en[son].second);
sta[son]=max(sta[son],sta[ne]);
en[son]=max(en[son],en[ne]);
}
}
int main()
{
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
int l,r;
for(int i=1;i<n;i++)
{
scanf("%d%d%s",&l,&r,s);
add(l,r,(int)s[0]),add(r,l,(int)s[0]);
}
scanf("%s",ss);
ans=mp(-1,-1);
dfs(1,0);
printf("%d %d\n",ans.first,ans.second);
return 0;
}