贪心算法 田忌赛马(problem C)

题意:这是田忌赛马的故事,首先可以将田忌和国王的马的速度从快到慢排列,然后进行比较。每比一次两边各减去一匹马,用四个标记分别标记田忌和国王的最快、最慢马。先比较他们最快的马,若相等,再比较最慢的马,考虑一下条件和其他因素就可以了。

#include"stdio.h"

#include"algorithm"
using namespace std;
const int N=1010;
int tian[N];
int king[N];
int cmp(int a,int b)
{
    return a>b;
}
int main()
{
    int n,i;
    while(scanf("%d",&n)&&n)
    {
        for(i=0;i<n;i++)
            scanf("%d",&tian[i]);
        for(i=0;i<n;i++)
            scanf("%d",&king[i]);
        sort(tian,tian+n,cmp);
        sort(king,king+n,cmp);
        int tfirst=0,kfirst=0,tlast=n-1,klast=n-1;
        int counta=0;
        for(i=0;i<n;i++)
        {
            if(tian[tfirst]>king[kfirst])
            {
                tfirst++;
                kfirst++;
                counta++;
            }
            else if(tian[tfirst]<king[kfirst])
            {
                tlast--;
                kfirst++;
                counta--;
            }
            else
            {
                if(tian[tlast]>king[klast])
                {
                    tlast--;
                    klast--;
                    counta++;
                }
                else if(tian[tlast]<king[klast])
                {
                    tlast--;
                    kfirst++;
                    counta--;
                }
                else
                {
                    if(tian[tlast]<king[kfirst])
                    {
                        tlast--;
                        kfirst++;
                        counta--;
                    }
                }
            }
        }
        printf("%d\n",counta*200);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_62089210/article/details/128042247