Bzoj 4567: [Scoi2016] Back Word dictionary tree + greedy

Source: Internet
Author: User
Test Instructions

Meaning is to put the word, each word must be placed before the suffix of the word first put up, the cost of each word is equal to the position of the word minus the last occurrence of the word suffix position
N<=100000,sigma (len) <=510000 Analysis

The first idea is to use a suffix array to build the map, if you want to really fight it is estimated that T. And also did not think how greedy ... is still too weak.

In fact, as long as a dictionary tree can handle the problem of building maps.
And then talk ... Every time I find a smaller subtree to go greedy. Prove it. It's not obvious. Code

#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <

Algorithm> #define N 100005 using namespace std;
int cnt,n,tim,size[n*10],last[n*20],ch[n*10][30],top,sta[n],val[n*10],tot,dfn[n*10];
Long long ans; struct Edge{int to,next;}
E[n];

Char s[n*10];
    void ins () {int Len=strlen (s), now=1;
        for (int i=len-1;i>=0;i--) if (ch[now][s[i]-' a ']) now=ch[now][s[i]-' a '];
    Else now=ch[now][s[i]-' a ']=++tot;
Val[now]=1;

} void Addedge (int u,int v) {e[++cnt].to=v;e[cnt].next=last[u];last[u]=cnt;}
    void build (int x,int y) {if (val[x]) Addedge (y,x), y=x;
for (int i=0;i<26;i++) if (Ch[x][i]) build (ch[x][i],y);
    } void Get_size (int x) {size[x]=1;
for (int i=last[x];i;i=e[i].next) get_size (e[i].to), size[x]+=size[e[i].to];

} BOOL cmp (int a,int b) {return size[a]<size[b];}
    void Dfs (int x) {dfn[x]=++tim;int l=top+1;
 for (int i=last[x];i;i=e[i].next) sta[++top]=e[i].to;   if (top<l) return;
    Sort (sta+l,sta+top+1,cmp);
    for (int i=l;i<=top;i++) DFS (Sta[i]), ans+=dfn[sta[i]]-dfn[x];
TOP=L-1;
    } int main () {scanf ("%d", &n);
    Tot=1;
        for (int i=1;i<=n;i++) {scanf ("%s", s);
    Ins ();
    } build (n);
    Get_size (1);
    DFS (1);
    printf ("%lld", ans);
return 0; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.