Topic: Given a tree, each node has a character, the number of characters from one node along the shortest path to another node.
No regrets in this life into the east, the afterlife is willing to birth fantasy Township
Topic Stamp Here
Note: the structure of the sun flower field is very special, only with a vacant space adjacent to the number of vacant space not more than 20
Quiz: ↑ What was your first reaction to seeing this sentence?
1. degree <=20
2. Number of leaf nodes <=20
Read it a few times and you'll find the answer.
[cover face bear] Teacher Chen is really a Chinese master ....
Number of leaf nodes <=20 what else to do ...
directly from each leaf node Dfs again, and then build the generalized suffix automaton, the final answer is the depth of each node deep-parent node
There is also an array of suffixes to DFS20 a trie tree, then build the trie tree into a suffix array (otz), and then just do it.
Otz
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define M 100100using namespace std;struct abcd{int to,next;} Table[m<<1];int head[m],tot;int n,c,a[m];long Long ans;int degree[m];void Add (int x,int y) {table[++tot].to=y; TABLE[TOT].NEXT=HEAD[X]; Head[x]=tot;} namespace suffix_automaton{struct sam{Sam *son[10],*parent; int MAX_DPT; BOOL V; void* operator New (size_t,int _) {#define L (1<<15) static Sam *mempool,*c; if (C==mempool) mempool= (c=new sam[l]) +l; c->max_dpt=_; c->parent=0x0; c->v=false; memset (c->son,0,sizeof C->son); return C + +; }}*root=new (0) Sam; sam* Extend (Sam *p,int x) {if (p->son[x]&&p->son[x]->max_dpt==p->max_dpt+1) retur N p->son[x]; Sam *np=new (p->max_dpt+1) Sam; WhilE (p&&!p->son[x]) p->son[x]=np,p=p->parent; if (!p) np->parent=root; else {Sam *q=p->son[x]; if (P->MAX_DPT+1==Q->MAX_DPT) np->parent=q; else {Sam *nq=new (p->max_dpt+1) Sam; nq->parent=q->parent; memcpy (nq->son,q->son,sizeof Nq->son); q->parent=nq;np->parent=nq; for (;p &&p->son[x]==q;p=p->parent) p->son[x]=nq; }} return NP; }}using namespace Suffix_automaton; Sam *node[m];void DFS (int x,int from) {int i; Node[x]=extend (Node[from],a[x]); for (I=head[x];i;i=table[i].next) if (table[i].to!=from) DFS (table[i].to,x);} void BFS () {static Sam *q[4004004]; int i,r=0,h=0; Q[++r]=root; while (r!=h) {Sam *p=q[++h]; if (p!=root) ANS+=P->MAX_DPt-p->parent->max_dpt; for (i=0;i<c;i++) if (p->son[i]&&!p->son[i]->v) P->son[i]->v=true,q[++r] =p->son[i]; }}int Main () {int i,x,y; cin>>n>>c; for (i=1;i<=n;i++) scanf ("%d", &a[i]); for (i=1;i<n;i++) {scanf ("%d%d", &x,&y); ADD (x, y); ADD (Y,X); degree[x]++; degree[y]++; } node[0]=root; for (i=1;i<=n;i++) if (degree[i]==1) DFS (i,0); BFS (); cout<<ans<<endl; return 0;}
Bzoj 3926 Zjoi2015 The gods favor the fantasy township suffix automaton