Problem c

来源:互联网 发布:淘宝怎么看卖家退款率 编辑:程序博客网 时间:2024/04/29 08:34
田忌赛马问题


The input consists of up to 50 test cases. Each case starts with a positive integer n (n <= 1000) on the first line, which is the number of horses on each side. The next n integers on the second line are the speeds of Tian’s horses. Then the next n integers on the third line are the speeds of the king’s horses. The input ends with a line that has a single 0 after the last test case.

Output
For each input case, output a line containing a single number, which is the maximum money Tian Ji will get, in silver dollars.

Sample Input
392 83 7195 87 74220 2020 20220 1922 180
根据网上的贪心算法的参考,分为三种情况:
(1)当田忌的最快的马比齐王最快的马快时,直接对决,赢一场。
(2)当田忌的最快的马比齐王最快的马慢时,那就用其最慢的马与齐王最快的马对决,废物最大话利用。
(3)当两者相等时,要分两种情况啦(a)当田忌的最慢的马比齐王最慢的马慢或者一样时,那就用其最慢的马与齐王最快的马对决。赢一场。
(b)当田忌的最慢的马比齐王最慢的马快,赢一场。
以下是我觉得对但是Runtime error的代码:
#include<iostream>#include<algorithm>#include<vector>using namespace std;bool cmp(int a,int b){    return a>=b;}int main(){    vector<int> a;//建立vector数组存放田忌的马    vector<int> b;    int n,money,win,tem;    int sum;    vector<int> ::iterator it1;//迭代器    vector<int> ::iterator it2;    while(cin>>n&&n<=1000)    {        if(n==0)            break;        win = 0;        money = 0;    for(int i = 0 ;i<n;++i)    {        cin>>tem;        a.push_back(tem);    }    for(int i = 0 ;i<n;++i)    {        cin>>tem;        b.push_back(tem);    }    sort(a.begin(),a.end(),cmp);//从大到小的排序    sort(b.begin(),b.end(),cmp);    for(int i = 0;n>0;i=0)//没比完一组,就从两者的数组中去掉,例如田的最慢马与齐的最快马比完就去掉两者    {        if(a[i] > b[i])        {           ++win;//赢了记录一场            it1 = a.begin()+i;            it2 = b.begin()+i;            a.erase(it1);//删除田忌的最快马            b.erase(it2);//删除齐王的最快马            --n;//各组马的数目减一
        }        else if(a[i] < b[i])        {            --win;//输一场,记录            it1 = a.begin()+n-1;删除田忌的最慢马            it2 = b.begin()+i;删除齐王的最快马            a.erase(it1);            b.erase(it2);            --n;        }        else//当两者相等时        {            if(a[n-1] < b[n-1])//            {                --win;                it1 = a.begin()+n-1;                it2 = b.begin()+i;                a.erase(it1);                b.erase(it2);                --n;            }            else if(a[n-1] > b[n-1])//田忌的最慢的马比齐王最慢的马快            {                ++win;
it1 = a.begin()+n-1;
            it2 = b.begin()+n-1;
            a.erase(it1);//删除田忌的最慢马
            b.erase(it2);//删除齐王的最慢马                --n;            }            else            {
  if(a[n-1] == b[i])                {                }                else                {                  --win;                }                it1 = a.begin()+n-1;                it2 = b.begin()+i;                a.erase(it1);                b.erase(it2);                --n;            }        }    }    money = win*200;    cout<<money<<endl;    }}
0 0
原创粉丝点击