使序列递增的最小交换次数
我们有两个长度相等且不为空的整型数组 A 和 B 。
我们可以交换 A[i] 和 B[i] 的元素。注意这两个元素在各自的序列中应该处于相同的位置。
在交换过一些元素之后,数组 A 和 B 都应该是严格递增的(数组严格递增的条件仅为A[0] < A[1] < A[2] < ... < A[A.length - 1])。
给定数组 A 和 B ,请返回使得两个数组均保持严格递增状态的最小交换次数。假设给定的输入总是有效的。
示例:
输入: A = [1,3,5,4], B = [1,2,3,7]
输出: 1
解释:
交换 A[3] 和 B[3] 后,两个数组如下:
A = [1, 3, 5, 7] , B = [1, 2, 3, 4]
两个数组均为严格递增的。
注意:
A, B 两个数组的长度总是相等的,且长度的范围为 [1, 1000]。
A[i], B[i] 均为 [0, 2000]区间内的整数。
这道题太难了

#include <vector> #include <iostream> using namespace std; class Solution { public: int minSwap(vector<int>& A, vector<int>& B) { int len= A.size(); int dp1[len]; //the times needed to make A, B sorted and A[i] >= B[i] int dp2[len]; //the times needed to make A, B sorted and A[i] <= B[i] if(A[0]>B[0]){ dp1[0]=0; dp2[0]=1; } else if (A[0]<B[0]) { dp1[0]=1; dp2[0]=0; } else{ dp1[0]=0; dp2[0]=0; } for (int i=1; i< len; i++){ int min_cur= min(A[i], B[i]); int max_pre= max(A[i-1], B[i-1]); if (min_cur> max_pre){ dp1[i]=min(dp1[i-1], dp2[i-1]); dp2[i]=min(dp1[i-1], dp2[i-1]); } else{ dp1[i]=dp1[i-1]; dp2[i]=dp2[i-1]; } if (A[i]<B[i]) dp1[i]+=1; else if (A[i]>B[i]) dp2[i]+=1; } return min(dp1[len-1], dp2[len-1]); } }; int main() { vector<int> A{4, 10, 13, 14, 17, 19, 21, 24, 26, 27, 28, 29, 34, 37, 38, 42, 44, 46, 48, 51, 52, 53, 54, 57, 58, 59, 64, 65, 66, 67, 71, 73, 75, 76, 80, 81, 82, 83, 86, 88, 89, 90, 95, 97, 98, 99, 101, 105, 106, 108, 109, 110, 111, 112, 115, 119, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 133, 136, 138, 143, 145, 147, 149, 150, 153, 158, 160, 163, 164, 165, 167, 168, 169, 172, 173, 174, 176, 178, 179, 183, 184, 186, 188, 189, 192, 193, 194, 198, 200}; vector<int> B{0, 1, 3, 5, 6, 7, 11, 13, 15, 16, 17, 21, 37, 39, 41, 42, 43, 45, 47, 50, 53, 55, 56, 57, 64, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 79, 80, 87, 88, 89, 95, 96, 97, 98, 100, 101, 105, 106, 107, 108, 112, 113, 115, 116, 118, 119, 122, 124, 125, 126, 127, 128, 131, 135, 136, 137, 138, 139, 140, 144, 145, 148, 150, 151, 154, 159, 160, 161, 162, 163, 167, 168, 170, 171, 174, 176, 178, 179, 180, 181, 185, 187, 189, 190, 191, 192, 198, 199, 200}; // vector<int> A{1, 3, 5, 4}; // vector<int> B{1, 2, 3, 7}; Solution s; cout << s.minSwap(A, B) << endl; }
浙公网安备 33010602011771号