hdu 3341 Lost's revenge(dp+Ac自动机)

题目:http://acm.hdu.edu.cn/showproblem.php?pid=3341

Lost's revenge

Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 3369    Accepted Submission(s): 896


Problem Description
Lost and AekdyCoin are friends. They always play "number game"(A boring game based on number theory) together. We all know that AekdyCoin is the man called "nuclear weapon of FZU,descendant of Jingrun", because of his talent in the field of number theory. So Lost had never won the game. He was so ashamed and angry, but he didn't know how to improve his level of number theory.

One noon, when Lost was lying on the bed, the Spring Brother poster on the wall(Lost is a believer of Spring Brother) said hello to him! Spring Brother said, "I'm Spring Brother, and I saw AekdyCoin shames you again and again. I can't bear my believers were being bullied. Now, I give you a chance to rearrange your gene sequences to defeat AekdyCoin!".

It's soooo crazy and unbelievable to rearrange the gene sequences, but Lost has no choice. He knows some genes called "number theory gene" will affect one "level of number theory". And two of the same kind of gene in different position in the gene sequences will affect two "level of number theory", even though they overlap each other. There is nothing but revenge in his mind. So he needs you help to calculate the most "level of number theory" after rearrangement.
 

Input
There are less than 30 testcases.
For each testcase, first line is number of "number theory gene" N(1<=N<=50). N=0 denotes the end of the input file.
Next N lines means the "number theory gene", and the length of every "number theory gene" is no more than 10.
The last line is Lost's gene sequences, its length is also less or equal 40.
All genes and gene sequences are only contains capital letter ACGT.
 

Output
For each testcase, output the case number(start with 1) and the most "level of number theory" with format like the sample output.
 

Sample Input
  
  
3 AC CG GT CGAT 1 AA AAA 0
 

Sample Output
  
  
Case 1: 3 Case 2: 2
做这题真的是闹心,只怪自己开始没有估计好时间复杂度瞎折腾,走了不少弯路。第一次想用Ac自动机检验长串的各种排列取最大值即可,但是长串有可能存在字符想通过的情况,排列一定小于length!,怎样才能把所有的非重复的字符串排列找出来呢?《C语言名题精选百则》里有个旋转法,但是我研究了半天也没有把重复的去掉。后来发现next_permutation是个好东西,可以除去重复的串,但前提是初始串是单调的,这简单,我用一个sort不就可以了吗?开心啊。。
TLE:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int ans;
char word[15],mystring[50];
struct node{
    int count;
    node *next[4],*fail;
    node(){
        count=0;
        fail=NULL;
        memset(next,0,sizeof(next));
    }
};
node *root;
int getdex(char a){
    int ans;
    if(a=='A')ans=0;
    else if(a=='C') ans=1;
    else if(a=='G') ans=2;
    else ans=3;
    return ans;
}
void insert(char *s){
    int length=strlen(s);
    node *p=root;
    for(int i=0;i<length;i++){
        int dex=getdex(s[i]);
        if(p->next[dex]==0)p->next[dex]=new node();
        p=p->next[dex];
    }
    p->count++;
}
node *que[1000];
void build_ac(){
    int head,tail;
    head=tail=0;
    que[tail++]=root;
    while(head<tail){
        node *p=que[head++],*temp=NULL;
        for(int i=0;i<4;i++){
            if(p->next[i]){
                if(p==root)p->next[i]->fail=root;
                else {
                temp=p->fail;
                while(temp){
                    if(temp->next[i]){
                        p->next[i]->fail=temp->next[i];
                        break;
                    }
                    temp=temp->fail;
                }
                if(!temp)p->next[i]->fail=root;
                }
                que[tail++]=p->next[i];
            }
        }
    }
}
void del(node *p){
    if(p==NULL)return ;
    for(int i=0;i<4;i++)del(p->next[i]);
    delete p;
}
int query(int str[],int str_len){
    int i,dex,result=0;
    node *p=root;
    for(i=0;i<str_len;i++){
        while(p->next[str[i]]==NULL&&p!=root)p=p->fail;
        p=p->next[str[i]];
        if(!p)p=root;
        node *temp=p;
        while(temp!=root){ //&&temp->count!=-1
            result+=temp->count;
            //temp->count=-1;
            temp=temp->fail;
        }
    }
    return result;
}
void show(int str[],int len){
    for(int i=0;i<len;i++)cout<<str[i]<<" ";  cout<<endl;
}
int main()
{
    //freopen("cin.txt","r",stdin);
    int n,ca=1;
    while(cin>>n&&n){
        root=new node();
        while(n--){
            scanf("%s",word);
            insert(word);
        }
        build_ac();
        scanf("%s",mystring);
        int str_len=strlen(mystring);
        int str[50];
        for(int i=0;i<str_len;i++){
            str[i]=getdex(mystring[i]);
        }
        int ans=0;
        sort(str,str+str_len);
        do{
            ans=max(ans,query(str,str_len));
        }while(next_permutation(str,str+str_len));
        printf("Case %d: %d\n",ca++,ans);
        del(root);
    }
    return 0;
}
郁闷啊,TLE了,是不是指针太耗时间了,于是我又把指针改成数组:
TLE:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int ans,top;
char word[15],mystring[50];
struct node{
    int next[4],fail;
    int count;
    node(){
        count=0;
        fail=NULL;
        memset(next,0,sizeof(next));
    }
}tree[510];
int getdex(char a){
    int ans;
    if(a=='A')ans=0;
    else if(a=='C') ans=1;
    else if(a=='G') ans=2;
    else ans=3;
    return ans;
}
void insert(char *s){
    int length=strlen(s),p=0;
    for(int i=0;i<length;i++){
        int dex=getdex(s[i]);
        if(tree[p].next[dex]==0){
            top++;
            tree[p].next[dex]=top;
        }
        p=tree[p].next[dex];
    }
    tree[p].count++;
}
void build_ac(){
    queue<int> q;
    q.push(0);
    int i,p,cur,son;
    while(!q.empty()){
        p=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            if(tree[p].next[i]){
                son=tree[p].next[i];
                if(p==0)tree[son].fail=p;
                else {
                    cur=tree[p].fail;
                    while(cur&&tree[cur].next[i]==0)cur=tree[cur].fail;
                    tree[son].fail=tree[cur].next[i];
                }
                if(tree[tree[son].fail].count)
                    tree[son].count+=tree[tree[son].fail].count;
                q.push(son);
            }
            else   tree[p].next[i]=tree[tree[p].fail].next[i];
        }
    }
}
int query(int str[],int str_len){
    int i,dex,result=0;
    int p=0;
    for(i=0;i<str_len;i++){
        while(tree[p].next[str[i]]==NULL&&p!=0)p=tree[p].fail;
        p=tree[p].next[str[i]];  //p=p->next[str[i]];
        if(!p)p=0;
        int temp=p;
        while(temp!=0){ //&&temp->count!=-1
            result+=tree[temp].count;
            //temp->count=-1;
            temp=tree[temp].fail;
        }
    }
    return result;
}
void show(int str[],int len){
    for(int i=0;i<len;i++)cout<<str[i]<<" ";  cout<<endl;
}
int main()
{
    //freopen("cin.txt","r",stdin);
    int n,ca=1;
    while(cin>>n&&n){
        //tree[0].node();
        while(n--){
            scanf("%s",word);
            insert(word);
        }
        build_ac();
        scanf("%s",mystring);
        int str_len=strlen(mystring);
        int str[50];
        for(int i=0;i<str_len;i++){
            str[i]=getdex(mystring[i]);
        }
        int ans=0;
        sort(str,str+str_len);
        do{
            ans=max(ans,query(str,str_len));
        }while(next_permutation(str,str+str_len));
        printf("Case %d: %d\n",ca++,ans);
        memset(tree,0,sizeof(tree));
    }
    return 0;
}
还是TLE!能不能愉快的玩耍了?仔细分析:原来40长度4种最小单位的长串排列估算有:40!/10!/10!/10!/10!=4.71e21,哎,一开始怎么不想想这个问题,还做了半天无用功!接下来怎么办呢?看了大神们的思路,DP啊,空间换时间。组合情况:11*11*11*11<15000。真是巧妙啊。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int ans,top;
char word[15],mystring[50];
struct node{
    int next[4],fail;
    int count;
}tree[510];
int getdex(char a){
    int ans;
    if(a=='A')ans=0;
    else if(a=='C') ans=1;
    else if(a=='G') ans=2;
    else ans=3;
    return ans;
}
void insert(char *s){
    int length=strlen(s),p=0;
    for(int i=0;i<length;i++){
        int dex=getdex(s[i]);
        if(tree[p].next[dex]==0){
            top++;
            tree[p].next[dex]=top;
        }
        p=tree[p].next[dex];
    }
    tree[p].count++;
}
void build_ac(){
    queue<int> q;
    q.push(0);
    int i,p,cur,son;
    while(!q.empty()){
        p=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            if(tree[p].next[i]){
                son=tree[p].next[i];
                if(p==0)tree[son].fail=p;
                else {
                    cur=tree[p].fail;
                    while(cur&&tree[cur].next[i]==0)cur=tree[cur].fail;
                    tree[son].fail=tree[cur].next[i];
                }
                if(tree[tree[son].fail].count)
                    tree[son].count+=tree[tree[son].fail].count;
                q.push(son);
            }
            else   tree[p].next[i]=tree[tree[p].fail].next[i];
        }
    }
}
int myhash[41][41][41][41];
int ta,tc,tg,tt;
int dp[15000][505];
void mydp(char *S)
{
    ta=tc=tg=tt=0;
    int i,j,k,l,num=0;
    for(i=0;S[i]!=0;i++)
        if(S[i]=='A')
            ta++;
        else if(S[i]=='C')
            tc++;
        else if(S[i]=='G')
            tg++;
        else
            tt++;
    for(i=0;i<=ta;i++)
        for(j=0;j<=tc;j++)
            for(k=0;k<=tg;k++)
                for(l=0;l<=tt;l++)
                    myhash[i][j][k][l]=num++;
}
void solve(int ca)
{
   int i,j,k,l,p,q,son,x1,x2,mmax=0;
   dp[0][0]=0;
   for(i=0;i<=ta;i++)
       for(j=0;j<=tc;j++)
           for(k=0;k<=tg;k++)
               for(l=0;l<=tt;l++)
               {
                   if(i+j+k+l==0)
                       continue;
                   x1=myhash[i][j][k][l];
                   for(p=0;p<=top;p++)
                   {
                       for(q=0;q<4;q++)
                       {
                           if(q==0&&i-1>=0)
                               x2=myhash[i-1][j][k][l];
                           else if(q==1&&j-1>=0)
                               x2=myhash[i][j-1][k][l];
                           else if(q==2&&k-1>=0)
                               x2=myhash[i][j][k-1][l];
                           else if(q==3&&l-1>=0)
                               x2=myhash[i][j][k][l-1];
                           else
                               continue;
                           if(dp[x2][p]==-1)
                               continue;
                           son=tree[p].next[q];
                           dp[x1][son]=max(dp[x1][son],dp[x2][p]+tree[son].count);
                           if(dp[x1][son]>mmax)
                               mmax=dp[x1][son];
                       }
                   }
               }
   printf("Case %d: ",ca);
   printf("%d\n",mmax);
}
int main()
{
    //freopen("cin.txt","r",stdin);
    int n,ca=1;
    while(cin>>n&&n){
        top=0;
        memset(dp,-1,sizeof(dp));
        while(n--){
            scanf("%s",word);
            insert(word);
        }
        build_ac();
        scanf("%s",mystring);
        mydp(mystring);
        solve(ca++);
        memset(tree,0,sizeof(tree));
    }
    return 0;
}
build_ac()内和普通的失败指针建立函数相比最重要的两句(//后面的两句):
   if(tree[tree[son].fail].count) ;
       //tree[son].count+=tree[tree[son].fail].count;
   q.push(son);
}
else   ;  //tree[p].next[i]=tree[tree[p].fail].next[i];
直接在建立失败指针时就更新各个节点的count。后面的状态转移过程直接使用。
普通的build_ac():
void build_ac(){
    queue<int> q;
    q.push(0);
    int i,p,cur,son;
    while(!q.empty()){
        p=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            if(tree[p].next[i]){
                son=tree[p].next[i];
                if(p==0)tree[son].fail=p;
                else {
                    cur=tree[p].fail;
                    while(cur&&tree[cur].next[i]==0)cur=tree[cur].fail;
                    tree[son].fail=tree[cur].next[i];
                }
                if(tree[cur])
                    tree[son].fail=0;
                q.push(son);
            }
        }
    }
}


### 回答1: hdu 2829 Lawrence 斜率优化dp 这道题是一道经典的斜率优化dp题目,需要用到单调队列的思想。 题目大意是给定一个序列a,求出一个序列b,使得b[i]表示a[1]~a[i]中的最小值,且满足b[i] = min{b[j] + (i-j)*k},其中k为给定的常数。 我们可以将上式拆开,得到b[i] = min{b[j] - j*k} + i*k,即b[i] = i*k + min{b[j] - j*k},这个式子就是斜率优化dp的形式。 我们可以用单调队列来维护min{b[j] - j*k},具体思路如下: 1. 首先将第一个元素加入队列中。 2. 从第二个元素开始,我们需要将当前元素加入队列中,并且需要维护队列的单调性。 3. 维护单调性的方法是,我们从队列的末尾开始,将队列中所有大于当前元素的元素弹出,直到队列为空或者队列中最后一个元素小于当前元素为止。 4. 弹出元素的同时,我们需要计算它们对应的斜率,即(b[j]-j*k)/(j-i),并将这些斜率与当前元素的斜率比较,如果当前元素的斜率更小,则将当前元素加入队列中。 5. 最后队列中的第一个元素就是min{b[j] - j*k},我们将它加上i*k就得到了b[i]的值。 6. 重复以上步骤直到处理完所有元素。 具体实现可以参考下面的代码: ### 回答2: HDU 2829 Lawrence 斜率优化 DP 是一道经典的斜率优化 DP 题目,其思想是通过维护一个下凸包来优化 DP 算法。下面我们来具体分析一下这道题目。 首先,让我们看一下该题目的描述。题目给定一些木棒,要求我们将这些木棒割成一些给定长度,且要求每种长度的木棒的数量都是一样的,求最小的割枝次数。这是一个典型的背包问题,而且在此基础上还要求每种长度的木棒的数量相同,这就需要我们在状态设计上走一些弯路。 我们来看一下状态的定义。定义 $dp[i][j]$ 表示前 $i$ 个木棒中正好能割出 $j$ 根长度为 $c_i$ 的木棒的最小割枝次数。对于每个 $dp[i][j]$,我们可以分类讨论: 1. 不选当前的木棒,即 $dp[i][j]=dp[i-1][j]$; 2. 选当前的木棒,即 $dp[i][j-k]=dp[i-1][j-k]+k$,其中 $k$ 是 $j/c_i$ 的整数部分。 现在问题再次转化为我们需要在满足等量限制的情况下,求最小的割枝次数。可以看出,这是一个依赖于 $c_i$ 的限制。于是,我们可以通过斜率优化 DP 来解决这个问题。 我们来具体分析一下斜率优化 DP 算法的思路。我们首先来看一下动态规划的状态转移方程 $dp[i][j]=\min\{dp[i-1][k]+x_k(i,j)\}$。可以发现,$dp[i][j]$ 的最小值只与 $dp[i-1][k]$ 和 $x_k(i,j)$ 有关。其中,$x_k(i,j)$ 表示斜率,其值为 $dp[i-1][k]-k\times c_i+j\times c_i$。 接下来,我们需要维护一个下凸包,并通过斜率进行优化。我们具体分析一下该过程。假设我们当前要计算 $dp[i][j]$。首先,我们需要找到当前点 $(i,j)$ 在凸包上的位置,即斜率最小值的位置。然后,我们根据该位置的斜率计算 $dp[i][j]$ 的值。接下来,我们需要将当前点 $(i,j)$ 加入到下凸包上。 我们在加入点的时候需要注意几点。首先,我们需要将凸包中所有斜率比当前点小的点移除,直到该点能够加入到凸包中为止。其次,我们需要判断该点是否能够加入到凸包中。如果不能加入到凸包中,则直接舍弃。最后,我们需要保证凸包中斜率是单调递增的,这就需要在加入新的点之后进行上一步操作。 以上就是该题目的解题思路。需要注意的是,斜率优化 DP 算法并不是万能的,其使用情况需要根据具体的问题情况来确定。同时,该算法中需要维护一个下凸包,可能会增加一些算法的复杂度,建议和常规 DP 算法进行对比,选择最优的算法进行解题。 ### 回答3: 斜率优化DP是一种动态规划优化算法,其主要思路是通过对状态转移方程进行变形,提高算法的时间复杂度。HDU2829 Lawrence问题可以用斜率优化DP解决。 首先,我们需要了解原问题的含义。问题描述如下:有$n$个人在数轴上,第$i$个人的位置为$A_i$,每个人可以携带一定大小的行李,第$i$个人的行李重量为$B_i$,但是每个人只能帮助没有他们重量大的人搬行李。若第$i$个人搬运了第$j$个人的行李,那么第$i$个人会累加$C_{i,j}=\left|A_i-A_j\right|\cdot B_j$的体力消耗。求$m$个人帮助每个人搬运行李的最小体力消耗。 我们可以通过斜率优化DP解决这个问题。记$f_i$为到前$i$个人的最小体力消耗,那么状态转移方程为: $$f_i=\min_{j<i}\{f_j+abs(A_i-A_j)\cdot B_i\}$$ 如果直接使用该方程,时间复杂度为$O(n^2)$,如果$n=10^4$,则需要计算$10^8$次,运算时间极长。斜率优化DP通过一些数学推导将方程变形,将时间复杂度降低到$O(n)$,大大缩短了计算时间。 通过斜率优化DP的推导式子,我们可以得到转移方程为: $$f_i=\min_{j<i}\{f_j+slope(j,i)\}$$ 其中,$slope(j,i)$表示直线$j-i$的斜率。我们可以通过如下方式来求解$slope(j,i)$: $$slope(j,i)=\frac{f_i-f_j}{A_i-A_j}-B_i-B_j$$ 如果$slope(j,i)\leq slope(j,k)$,那么$j$一定不是最优,可以直接舍去,降低计算时间。该算法的时间复杂度为$O(n)$。 综上所述,斜率优化DP是一种动态规划优化算法,可以大大缩短计算时间。在处理类似HDU2829 Lawrence问题的时候,斜率优化DP可以很好地解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值