csu 1538: Shopping(贪心)

#include<iostream>

#include<cstdio>

#include<cstring>

#include<cmath>

#include<stdlib.h>

#include<queue>

#include<algorithm>

#include<vector>

#include<ctype.h>

#define LL __int64

using namespace std;

const double EPS=1e-9;

const int MAXN=1000+10;

int vis[2000];

int gcd(int a,int b)

{

    return b?gcd(b,a%b):a;

}

int lcm(int a,int b)

{

    return a/gcd(a,b)*b;

}

typedef struct good

{

    int c;

    int d;

};

int main()

{

    int n,m;

    int i,j,k;

    int fl[MAXN],fr[MAXN];

    good p[MAXN];

 

    while(scanf("%d%d",&n,&m)!=EOF)

    {

        memset(vis,0,sizeof(vis));

        int exit=n+1,enter=0,start=0;

       for( i=1;i<=n;i++)

        {

            fl[i]=fr[i]=i;

        }

       for( i=1;i<=m;i++)

        {

            scanf("%d %d",&p[i].c,&p[i].d);

            vis[p[i].c]=1;

            vis[p[i].d]=1;

            fl[p[i].d]=p[i].c;

            fr[p[i].c]=p[i].d;

        }

        int flag=0;

        int ans=0;

        int  L=0,R=0;

        int last=0;

        for(i=1;i<=n+1;i++)

        {

            if(vis[i]==0)

            continue;

            if(flag==0)

            {

                flag++;

                ans+=(i-last);

                //printf(" %d  %d///\n",i,ans);

                L=i;

                R=fr[i];

            }

            else if(R<fl[i])

            {

                ans+=(R-L)*3;

                ans+=(i-R);

                //flag--;

                L=fl[i];

                R=fr[i];

                last=i;

                //printf("%d %d\n",i,ans);

            }

            else if(fl[i]<R&&R<fr[i])

            {

                R=fr[i];

            }

        }

        //printf("%d\n",ans);

        ans+=(n+1-R);

        //printf("%d\n",ans);

        ans+=(R-L)*3;

        printf("%d\n",ans);

    }

 

 

 

    return 0;

}

  

你可能感兴趣的:(ping)