Subject description:
Input two arrays of integers A and B, both of the elements satisfy the unique and random, while the elements of A are present in the B, B, is also present in A, i.e., A and B, only the order of elements may be different, For example, (1,3,5,2) and (3,2,1,5).
Are now want to delete part of the element A and B, such that A and B are the same as the rest of the sequence, output a minimum number of elements in the array A to be deleted (note array B need to remove the same number of elements).
Enter a description:
Input common three lines, a first line integer n (1 <= n <= 100000), A and B represents the number of elements. The second line array A, a total of n integers, the behavior of the third array B, a total of n integers.
Output Description:
The output of a number of elements in the array A behavior you want to delete (contain newline).
Input:
4
1 3 5 2
3 2 1 5
Output:
2
Description:
{1, 3, 5, 2}, and {3, 2, 1, 5} of the three longest common subsequence. Are {1, 5}, {3, 5}, {3, 2}, so the need to remove at least two elements.
Analysis of ideas:
First, using a hash table to save each element in the array A, B according to the input of the next, by the A array to hold the position of the corresponding element in the B. For the essence A, B is equal to the need to find elements both increase in the longest sequences.
Code:
1 #include<stdio.h> 2 #include<iostream> 3 #include<vector> 4 #include<algorithm> 5 #include<string> 6 #include<map> 7 #include<limits.h> 8 #include<queue> 9 using namespace std; 10 11 int LIS(vector<int>&A, vector<int>&B) 12 { 13 int len=1; 14 B[0]=A[0]; 15 for(int i=1; i<A.size(); i++) 16 { 17 if(A[i]>B[len-1]) 18 B[len++]=A[i]; 19 else 20 { 21 int p = lower_bound(B.begin(), B.begin()+len, A[i])-B.begin(); 22 B[p] = A[i]; 23 } 24 } 25 return len; 26 } 27 28 int main() 29 { 30 int n; 31 cin>>n; 32 vector<int>A(n); 33 vector<int>B(n); 34 map<int, int>M; 35 for(int i=0; i<n; i++) 36 { 37 cin>>A[i]; 38 M[A[i]]=i; 39 } 40 int k=0; 41 for(int i=0; i<n; i++) 42 { 43 int x; 44 cin>>x; 45 A[M[x]] = k++; 46 } 47 int ans = n-LIS(A,B); 48 cout<<ans<<endl; 49 return 0; 50 }