POJ 4044 寻找最长连续公共子序列
2012-05-10 08:31 javaspring 阅读(279) 评论(0) 编辑 收藏 举报题意很简单,就是对两组数据排序后寻找最长连续公共子序列,排序前应该先去重。由于数据范围很小(30),所以可以完全暴力求解。随后将最长连续公共子序列的各个数按各位升序排序即可。
ac代码:
#include <iostream> #include <cstdio> #include <algorithm> #include <string.h> using namespace std; const int N = 35; int numa[N],numb[N]; bool cmp(int a,int b){ return a>b; } bool cmp2(int a,int b){ if(a%10 == b%10) return a<b; return a%10 < b%10; } int main(){ //freopen("1.txt","r",stdin); int numcase,n,m; scanf("%d",&numcase); for(int k = 1;k <= numcase;++k){ memset(numa,-1,sizeof(numa)); memset(numb,-1,sizeof(numb)); scanf("%d%d",&n,&m); for(int i = 0;i < n;++i){ scanf("%d",&numa[i]); for(int j = 0;j < i;++j){ if(numa[j] == numa[i]){ i--; n--; } } } for(int i = 0;i < m;++i){ scanf("%d",&numb[i]); for(int j = 0;j < i;++j){ if(numb[j] == numb[i]){ i--; m--; } } } sort(numa,numa+n,cmp); sort(numb,numb+m,cmp); int mmax = 0,abegin=0,aend=0; for(int i = 0;i < n;++i){ for(int j = 0;j < m;++j){ if(numa[i] == numb[j]){ int k = 0; while(i+k < n && j+k < m && numa[i+k] == numb[j+k]){ k++; } if(k > mmax){ mmax = k; abegin = i; aend = i + k; } } } } if(mmax == 0)puts("NONE"); else{ for(int i = abegin;i < aend;++i) printf("%d ",numa[i]); printf("\n"); sort(numa+abegin,numa+aend,cmp2); for(int i = abegin;i < aend;++i) printf("%d ",numa[i]); printf("\n"); } } return 0; }