I have the following task:
Given a set of N positive numbers. Write a program which finds the middle element of the set.
Input: on the first line there are number of examples,
the second line is for the length of the set. The next line is for the numbers of the set separated with space.
Something line this:
2 (number of examples)
5 (length)
12 4 22 31 32 (set)
8 (length)
22 33 44 11 55 66 88 99 (set)
Then you have to sort the set and print the middle element.
Output:
22 (mid elem of first set)
44 (mid elem of second set)
Constraints: N < 10^11 and each number of set should be < 10^20
So i choose to work directly with strings because of the big numbers. Here is my code:
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cstring>
using namespace std;
bool comparer (const string s1, const string s2)
{
return atoi(s1.c_str()) < atoi(s2.c_str());
}
int main()
{
int numberOfExamples;
cin >> numberOfExamples;
for (int i = 0; i < numberOfExamples; i++)
{
long length;
string input;
cin >> length;
string buffer;
while(getline(cin, input))
{
vector<string> v;
istringstream is(input);
while (is >> buffer) v.push_back(buffer);
sort (v.begin(), v.end(), comparer);
string middle;
if (v.size() % 2 == 0)
{
middle = v[v.size()/2 -1];
}
else
{
middle = v[v.size()/2];
}
cout << middle;
}
}
return 0;
}
And after compiling it stop on the second row for inputing the length of the first example and i got the error of type 0xC00000005. Any help would be appreciated.