Jimi Hendrix—— 樹上dfs搜包含目標串的兩個端點
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; }