Median of two ordered sequences of 7-1 (25 points)
It is known that there are two equal length non-descending sequence S1, S2. The design function calculates the median of the union of S1 and S2. Ordered sequence A0,A1,... The median of An-1 is the value of A(N1)/2, that is, the number of [(N+1)/2] (A0 is the first number).
Input format:
The input is divided into three lines. The first line gives the common length N of the sequence (0 < N < 100000), and then each line enters the information of the sequence, that is, N non-descending integers. Numbers are spaced by spaces.
Output format:
Output the median of the union sequence of two input sequences in a row.
Input Sample 1:
5
1 3 5 7 9
2 3 4 5 6
Output Sample 1:
4
Input Sample 2:
6
-100 -10 1 1 1 1
-50 0 2 3 4 5
Wrong thinking:
Because of this problem, we want to put two rows of arrays together and add and delete them with set sort.
But the meaning of union in question is merging, not deleting.
Error code:
#include<iostream> #include<cstdio> #include<set> using namespace std ; int main () { int a ; int n ; set<int>s1 ; cin >> n ; for ( int i = 0 ; i < n*2 ; i++ ) { cin >> a ; s1.insert(a) ; } /* //Error: for( int i = 0 ; i < s1.size() ; i++ ) { cout << *s1.begin()+i << " " ; } //Correct: set<int>::iterator it ; //container for ( it = s1.begin() ; it != s1.end() ; it++) { printf( "%d ",*it) ; } */ int num = s1.size() ; set<int>::iterator it ; //container it = s1.begin() ; if ( num % 2 == 0 ) { // float sum = ((*it+(num/2-1))+ (*it+(num/2)))/2.0 ; int sum = *it+(num/2-1); cout << sum ; } else cout << *it+((num+1)/2-1) ; return 0 ; }
Correct thinking:
After pressing two arrays into the vector stack, sort the median.
Correct code:
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector<int> C;//Union of two sequences int n,data1,data2; cin>>n; for(int i=0; i<n; i++) { cin>>data1; C.push_back(data1); } for(int i=0; i<n; i++) { cin>>data2; C.push_back(data2); } sort(C.begin(),C.end()); //Ascending Sort, Unbubbling cout<<C[n-1]; }
Be careful:
The median here refers not to the sum of the middle two digits divided by two, but to the left of the middle two digits!