Poj Solution 1944

http://poj.org/problem?id=1944

#include <stdio.h>
#include <algorithm>
#include <memory.h>
using namespace std;
int t[4100];
int sum[4100];
void insert( int l, int r, int a, int b, int s, bool del )
{
    int c = (l+r)/2;
    if( l>=r || l>=b || r<=a ) return;
    if( a<=l && r<=b )
    {
        if(del)
        {
            t[s]--;
            if( !t[s] ) sum[s] = (r-l==1) ? 0 : ( sum[s*2+1] + sum[s*2+2] );
        }
        else 
        {
            t[s]++;
            sum[s] = r - l;
        }
        return;
    }
    insert( l, c, a, b, s*2+1, del );
    insert( c, r, a, b, s*2+2, del );
    if( !t[s] )    sum[s] = sum[s*2+1] + sum[s*2+2];
}
typedef pair<int,int> seg;
seg h[20010];
int n, p;
void init()
{
    int i;
    scanf( "%d %d", &n, &p );    
    memset( t, 0, 4100*sizeof(int) );
    memset( sum, 0, 4100*sizeof(int) );
    for( i=0; i<p; i++ )
    {
        scanf( "%d %d", &h[i].first, &h[i].second );
        
        h[i].first--, h[i].second--;

        if( h[i].first > h[i].second ) swap( h[i].first, h[i].second );

        insert( 0, 2048, h[i].first, h[i].second, 0, false );
        
        h[i+p].first = h[i].second;
        h[i+p].second = h[i].first+n;
    }

    p*=2;
    
    sort( h, h+p );


}
int main()
{
    int i, ans, j;
    init();    
    ans = 10000;
    for( i=0, j=0 ; i<n; i++ )
    {
        if( sum[0] < ans ) ans = sum[0];
        while( j < p && h[j].first <= i )
        {
            insert( 0, 2048, h[j].first, h[j].second, 0, true );
            insert( 0, 2048, h[j].second, h[j].first+n, 0, false );
            j++;
        }
    }
    printf( "%dn", ans );
    return 0;
}


											
This entry was posted in poj. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *