Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I got a problem from UVA online judge Problem link. I have read it tons of times and as they said, I have to get the answer really fast.

I have used a binary search and STD::Sort, but I am still having time error. I don't know any faster way to search on an array than binary search.

Any feedback please?

PS:I am not an english speaker, sorry for my english.

#include <stdio.h>
#include <string>
#include <algorithm>

int n,q,vec[100000];
int inicio,final,medio,busca;
int cont;
int busquedabinaria()
{

    //busqueda binaria
    std::sort(vec,vec+n);
    inicio=0;
    final=n-1;
    medio=(inicio+final)/2;

    while(inicio<=final)
    {
        if(vec[inicio]==busca)
            return inicio;
        if(vec[medio]==busca)
            return medio;
        if(vec[final]==busca)
            return final;
        medio = (inicio + final) / 2;
        if (vec[medio] > busca)
            final = medio - 1;
        else if (vec[medio] < busca)
            inicio = medio + 1;
        // found

    }
    return -1;

}

int main() 
{

    freopen("in.txt", "rt",stdin);
    freopen("out.txt", "wt",stdout);

    while (scanf("%d %d\n",&n,&q)!=EOF && (n!=0 || q!=0)    )
    {
        for (int i=0;i<n;i++)
        {
            scanf("%d\n",&vec[i]);

        }
        printf("CASE# %d:\n",cont+1);
        cont++;
        while(q--)
        {

        scanf("%d\n",&busca);

            int res=busquedabinaria();
            if(res!=-1)
            {
                while (vec[res-1]==busca && res>0)
                {
                    res--;
                }
                printf("%d found at %d\n",busca,res+1);

        }
            else 
                printf("%d not found\n",busca);

        }

    }

    return 0;
}
share|improve this question
I know that in UVa OJ, your program should read from standard input and write to standard output. You are reading from "in.txt" so no input is provided to your program and it hangs till getting TLE. – saeedn Sep 30 '12 at 13:32
Yes, but thats just for debbuging, when you submit it you should erease it – Giuseppe Sep 30 '12 at 17:02
1  
The problem is you have applied a brute force technique to the problem. The quickest solution would be to work out a formula that allows you to calculate the count of each number. When Your input is 1 9999999 this technique will be infinitely quicker than a brute force approach. – Loki Astari Oct 1 '12 at 15:58
Do you want this code analysed as C++? Also, English identifiers would help. – Anton Golov Oct 2 '12 at 7:15

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.