topcoder SRM 594 DIV2 AstronomicalRecordsEasy

OpenSoucre發表於2013-10-19

此題主要考查的是求最長公共子序列

設A[i]:A[j] = a:b = ac:bc       B[ii]:B[jj] = c:d = ac:ad ,

如果A[i]:A[j] = B[ii]:B[jj]則bc= ad,所以A乘以B的倍數,B乘以A的倍數,則A與B所求的序列必然是一樣的,即求A與B的最長公共子序列

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 class AstronomicalRecordsEasy{
 8 public:
 9     int minimalPlanets(vector<int> A, vector<int> B){
10         int lenA = A.size(),lenB = B.size(),res = lenA + lenB;
11         for(int i = 0; i < lenA; ++ i ){
12             for(int  j = 0 ; j < lenB; ++ j){
13                 int a = A[i],b = B[j];
14                 vector<vector<int> > dp(lenA+1,vector<int> (lenB+1,0));
15                 for(int ki = 1; ki <= lenA; ++ ki ){
16                     for(int kj = 1; kj <= lenB; ++ kj){
17                         dp[ki][kj] = max(max(dp[ki-1][kj],dp[ki][kj-1]),dp[ki-1][kj-1] + (b*A[ki-1] == a*B[kj-1]) );
18                     }
19                 }
20                 res = min(res, lenA+lenB - dp[lenA][lenB]);
21             }
22         }
23         return res;
24     }
25 };

相關文章