HDU 1160 FatMouse's Speed

题解:最长上升子序列的应用,按w升序,s降序排列后进行DP找最长序列,用pre[]数组记录该点的前驱,从而打印路径

#include <cstdio>  

#include <algorithm>  

using namespace std;  

struct mouse{  

    int w,s,id;  

    bool operator<(const mouse& m) 

    const{  

        return w<m.w||(w==m.w&&s>m.s);    

    }     

}m[1005];  

int d[1005],pre[1005],ms=1,ans[1005];  

void solve(){  

    d[0]=-1;  

    int head=0;  

    for(int i=1;i<=ms;i++){  

        int t=0;  

        for(int j=1;j<i;j++){  

            if(m[i].w>m[j].w&&m[i].s<m[j].s&&d[j]+1>d[t]+1){  

                t=j;  

            }     

        }  

        if(t==0)d[i]=1,pre[i]=-1;  

        else{  

            d[i]=d[t]+1;  

            pre[i]=t;  

        }  

        if(d[i]>d[head])head=i;   

    }       

    int as=0;  

    while(head!=-1){  

        ans[as++]=m[head].id;  

        head=pre[head];     

    }  

    printf("%d\n",as);  

    for(int i=as-1;i>=0;i--)printf("%d\n",ans[i]);  

}  

int main()

{  

    while(scanf("%d%d",&m[ms].w,&m[ms].s)!=EOF)m[ms].id=ms,ms++;  

    sort(m+1,m+ms+1);        

    solve();  

    return 0;     

}  

 

你可能感兴趣的:(HDU)