http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=524
LCS 细节
View Code
#include <iostream> #include <cstdio> #include <vector> #include <cmath> #include <set> #include <map> #include <queue> #include <string> #include <cstring> #include <algorithm> //int f_min(int x,int y) {if(x<y)return x; else return y;} //int f_max(int x,int y) {if(x<y)return y; else return x;} //int f_abs(int x) {return (x)>(0)?(x):(-x);} int lowbit(int x) {return (x)&(-x);} double f_min(double x,double y) {if(x<y)return x; else return y;} double f_max(double x,double y) {if(x<y)return y; else return x;} using namespace std; const int MM = 511111; const double Pi = acos(-1.0); const double lep = 1e-6; const double inf = 1000000000.00; #define debug puts("wrong") #define maxint 0x3f3f3f3f #define lson rt<<1 #define rson rt<<1|1 //typedef __int64 int64; //typedef long long int64; //const __int64 maxint = 1000000000000000; int N,M; int num[MM], Q; int list[MM]; struct Info { int id; double val; }p[MM]; struct Union_set { int fa[MM]; int rank[MM]; void reset(int n) { for(int i=0;i<=n;i++) { fa[i]=i; rank[i]=0; } } int getfa(int x) {return fa[x]==x?x:fa[x]=getfa(fa[x]);} void join(int x,int y) { int xx=getfa(x), yy=getfa(y); if(xx==yy) return; else { if(rank[xx]>rank[yy]) fa[yy]=xx; else { if(rank[xx]<rank[yy]) fa[xx]=yy; else { fa[xx]=yy; rank[yy]++; } } } } }Unset; double dp[2][MM]; void get_data() { int i,j,k; for(i=1;i<=N;i++) scanf("%d",&list[i]); for(i=1;i<=M;i++) scanf("%d%lf",&p[i].id,&p[i].val); } void solve() { int i,j,k; int now=0, pre=1; for(i=0;i<=M;i++) dp[now][i]=inf; for(i=1;i<=M;i++) { if(p[i].id==list[1]) dp[now][i]=f_min(dp[now][i-1],p[i].val); else dp[now][i]=dp[now][i-1]; } // for(i=1;i<=M;i++) printf("%.2lf ",dp[now][i]); printf("\n"); for(i=2;i<=N;i++) { for(j=0;j<=M;j++) dp[pre][j]=inf; for(j=1;j<=M;j++) { if(p[j].id==list[i]) dp[pre][j]=f_min(dp[pre][j-1],dp[now][j-1]+p[j].val); else dp[pre][j]=dp[pre][j-1]; } now=pre, pre^=1; } double ans=inf; for(i=0;i<=M;i++) { if(ans>dp[now][i]) ans=dp[now][i]; } if(ans<inf) printf("%.2lf\n",ans); else puts("Impossible"); } int main() { while(scanf("%d%d",&N,&M),N+M) get_data(),solve(); return 0; }