Cod sursa(job #1709959)

Utilizator UPB_CodeJunkiesUPB NAIDEN NICOLICIOIU COTET UPB_CodeJunkies Data 28 mai 2016 14:35:34
Problema Padure2 Scor 100
Compilator cpp Status done
Runda ONIS 2016 - Runda - 2 - ACM ICPC Romanian Programming Contest Marime 1.97 kb
#include <stdio.h>
#include<algorithm>
#define mp make_pair
#define maxn 2000015
#define maxc 1005
#define MOD 2000003
using namespace std;

int n,m,C;
int f[maxn],inv[maxn],used[maxn], dp[maxc];
pair<int,int> a[maxc];

bool cmp(const pair<int,int> &A,const pair<int,int> &B)
{
    if( A.first==B.first ) return A.second<B.second;
    return A.first<B.first;
}

void read()
{
    int x,y;

    scanf("%d %d",&n,&m);
    scanf("%d",&C);
    for(int i=1;i<=C;i++)
    {
        scanf("%d %d",&x,&y);
        a[i]=mp(x,y);
    }

    sort(a+1,a+C+1,cmp);
}

void gcd(long long a,long long b,long long &x,long long &y)
{
    if(b==0) {x=1; y=0; return;}

    long long x0,y0;
    gcd(b,a%b,x0,y0);
    x=y0; y=x0-(a/b)*y0;
}

void preproc()
{
    f[0]=1; inv[0]=1;
    for(int i=1;i<=2000010;i++)
        f[i]=(1LL*f[i-1]*i)%MOD;
}

long long comb(long long a,long long b)
{
    long long x,y;

    if( !used[a-b] )
    {
        gcd(f[a-b],MOD,x,y);

        while(x<0) x+=MOD;
        inv[a-b]=x%MOD;

        used[a-b]=1;
    }

    if( !used[b] )
    {
        gcd(f[b],MOD,x,y);

        while(x<0) x+=MOD;
        inv[b]=x%MOD;

        used[b]=1;
    }

    long long res = (1LL*f[a]*inv[b])%MOD;
    res= (1LL*res*inv[a-b])%MOD;

    return res;
}

void solve()
{
    a[++C]=mp(n,m);

    int x,y;
    for(int i=1;i<=C;i++)
    {
        x=a[i].first; y=a[i].second;
        dp[i]=comb(x+y-2, y-1);

        for(int j=1;j<i;j++)
         if( a[j].first<=x && a[j].second<=y )
         {
             long long xx = x-a[j].first+1;
             long long yy = y-a[j].second+1;
             long long p = comb(xx+yy-2, yy-1);

             dp[i]-= (1LL*dp[j]*p)%MOD;
             while(dp[i]<0 ) dp[i]+=MOD;
         }
    }

    printf("%d ",dp[C]);
}

int main()
{
    freopen("padure2.in","r",stdin);
    freopen("padure2.out","w",stdout);

    preproc();
    read();
    solve();

    return 0;
}