http://blog.csdn.net/ice_crazy/article/details/8244639
这里5000*5000超出内存,所以需要用滚动数组:
用一个now表示当前的结果,pre表示前一个的结果,不断滚动即可
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <stack> #include <queue> #include <cctype> #include <vector> #include <iterator> #include <set> #include <map> #include <sstream> using namespace std; #define mem(a,b) memset(a,b,sizeof(a)) #define pf printf #define sf scanf #define spf sprintf #define pb push_back #define debug printf("!\n") #define MAXN 5005 #define MAX(a,b) a>b?a:b #define blank pf("\n") #define LL long long #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) #define pqueue priority_queue #define INF 0x3f3f3f3f int n,m; char a[MAXN],b[MAXN]; int dp[2][MAXN]; int lcs(int al) { int i,j; int now,pre; for(i=1;i<=al;i++) { for(j=1;j<=al;j++) { now = i%2; pre = 1-now; if(a[i-1] == b[j-1]) dp[now][j] = dp[pre][j-1]+1; else dp[now][j] = max(dp[pre][j],dp[now][j-1]); } } return al-dp[al%2][al]; } int main() { int i,j; while(~sf("%d",&n)) { mem(dp,0); sf("%s",a); strcpy(b,a); strrev(b); pf("%d\n",lcs(n)); } }
时间: 2024-10-27 12:01:30