topcoder SRM 594 DIV2 AstronomicalRecordsEasy
此题主要考查的是求最长公共子序列
设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 };