Search code examples
c++c++11vectorruntime-errormedian

Stuck at What is the median UVa 10107


I am stuck at this uva problem i think my algorithm is right but the program crashes on running , I can't figure out where the problem is but i think it is with the iterator ??! Any help please !!!

Code:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
    int n, R, L;

    long long idx, aver;
    std::vector<long long> v;
    std::vector<long long>::iterator it;

    while(cin >> n)
    {
        it=v.begin();
        v.push_back(n);
        std::sort(v.begin(), v.end());

        if(v.size() == 1)
        {
            std::cout << *it << std::endl;
        }
        else if(v.size() % 2 == 0)
        {
            L=v.size() / 2 - 1;
            R=v.size() / 2;

            aver = (*(it + L) + *(it + R)) / 2;

            std::cout<< aver << std::endl;
        }
        else
        {
            idx = v.size() / 2;
            aver = *(it + idx);

            std::cout << aver << std::endl;
        }
    }

    return 0;
}

Problem link

Ideone link


Solution

  • I got it I finally got accepted , the problem was with the iterator , it pointed to v.begin() when the vector was empty at the first iteration of the loop so the program crashed . I made the iterator to point to the beginning of the vector after doing the first push_back() , where the vector is not empty at this case.

    Right Code:

    #include<iostream>
    #include<algorithm>
    #include <vector>
    using namespace std;
    int main()
    {
        int n,R,L;
        long long idx,aver;
        vector<long long>v;
        vector<long long>::iterator it;
    
        while(cin>>n)
        {
    
            v.push_back(n);
            it=v.begin();
            sort(v.begin(),v.end());
    
    
    
            if(v.size()==1){
                cout<<*it<<endl;
            }
            else if(v.size()%2==0)
            {
                L=v.size()/2-1;
                R=v.size()/2;
    
                aver=(*(it+L)+*(it+R))/2;
    
                cout<<aver<<endl;
            }
            else
            {
                idx=v.size()/2;
                aver=*(it+idx);
    
                cout<<aver<<endl;
            }
        }
        return 0;
    }
    

    Ideone link