Cod sursa(job #568261)

Utilizator MciprianMMciprianM MciprianM Data 30 martie 2011 23:37:58
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include<fstream>

using namespace std;

const int p1 = 411113, p2 = 411113;

unsigned t1 [ p1 ] [ 4 ];
unsigned t2 [ p2 ] [ 4 ];

unsigned search ( unsigned x ) {
    int i, h1, h2;
    h1 = x % p1;
    h2 = x % p2;
    for ( i = 0; i < 4 && t1 [ h1 ] [ i ]; ++ i )
        if ( t1 [ h1 ] [ i ] == x )
            return 1;
    for ( i = 0; i < 4 && t2 [ h2 ] [ i ]; ++ i )
        if ( t2 [ h2 ] [ i ] == x )
            return 1;
    return 0;
}

void insert ( unsigned x ) {
    int i, h1, h2, l1, l2;
    h1 = x % p1;
    h2 = x % p2;
    for ( i = 0; i < 4 && t1 [ h1 ] [ i ]; ++ i );
    l1 = i;
    for ( i = 0; i < 4 && t2 [ h2 ] [ i ]; ++ i );
    l2 = i;
    if ( l1 == 4 || l1 > l2 ) {
        if ( l2 == 4 )
            exit ( 1 );
        t2 [ h2 ] [ l2 ] = x;
    }
    else {
        t1 [ h1 ] [ l1 ] = x;
    }
}

void erase ( unsigned x ) {
    int i, h1, h2;
    h1 = x % p1;
    h2 = x % p2;
    for ( i = 0; i < 4 && t1 [ h1 ] [ i ]; ++ i )
        if ( t1 [ h1 ] [ i ] == x )
            break;
    if ( i < 4 && t1 [ h1 ] [ i ] ) {
        while ( i < 3 ) {
            t1 [ h1 ] [ i ] = t1 [ h1 ] [ i + 1 ];
            i ++;
        }
        return;
    }
    for ( i = 0; i < 4 && t2 [ h2 ] [ i ]; ++ i )
        if ( t2 [ h2 ] [ i ] == x )
            break;
    if ( i < 4 && t2 [ h2 ] [ i ] ) {
        while ( i < 3 ) {
            t2 [ h2 ] [ i ] = t2 [ h2 ] [ i + 1 ];
            i ++;
        }
        return;
    }
}


int main(){
    int n, i;
    unsigned int found, x, cod;
    ifstream f ( "hashuri.in" );
    ofstream g ( "hashuri.out" );
    f >> n;
    for ( i = 0; i < n; ++ i ) {
        f >> cod >> x;
        if ( cod == 1 ) {   // insert
            found = search ( x );
            if ( ! found )
                insert ( x );
        }
        else
            if ( cod == 3 ) {   // find
                found = search ( x );
                g << found << '\n';
            }
            else
                if ( cod == 2 ) {   //del
                    erase ( x );
                }
    }
    f.close();
    g.close();
    return 0;
}