Puzzle
Time Limit: 2 Seconds Memory Limit: 65536 KB
For sequences of integers a and b, if you can make the two sequences the same by deleting some elements in a and b, we call the remaining sequence "the common sub sequence". And we call the longest one the LCS.
Now you are given two sequences of integers a and b. You can arrange elements in a and b in any order. You are to calculate the max length of the LCS of each arrangement of a and b.
Input
Input will consist of multiple test cases. The first line of each case is two integers N(0 < N < 10000), M(0 < M < 10000) indicating the length of a and b. The second line is N 32-bit signed integers in a. The third line is M 32-bit signed integers in b.
Output
Each case one line. The max length of the LCS of each arrangement of a and b.
Sample Input
5 4
1 2 3 2 1
1 4 2 1
Sample Output
3
思路:刚开始以为是dp结果段错误,有一句话是 : 顺序可以自由变化 ,所以排序暴力即可
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 1e4 + 5;
int a[MAX], b[MAX];
int main()
{
int n, m;
while(cin >> n >> m){
for (int i = 0; i < n; i++){
cin >> a[i];
}
for (int i = 0; i < m; i++){
cin >> b[i];
}
sort(a, a + n);
sort(b, b + m);
int res = 0;
int update = 0;
for (int i = 0; i < n; i++){
for (int j = update; j < m; j++){
if (a[i] == b[j]){
update = j + 1;
res++;
break; //这里是break不是continue
}
}
}
cout << res << endl;
}
return 0;
}