Section 1.3 Barn Reapir

贪心算法,思路不难但在提交过程中发现很多bug:
1.得到需要“切板”的位置后,应该按num排序
2.当M == 1时要特别处理,否则number为空向量,程序异常退出
3.输入牛的位置是无序的,要先按num升序排序
4.当M > C的时候,number个数应该为min(M,C)

/*
ID: alexyua2
PROG: barn1
LANG: C++
*/

#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;

ifstream fin("barn1.in");
ofstream fout("barn1.out");

//ifstream fin("in.txt");
//ofstream fout("out.txt");

struct Stall
{
    int num;
    int interval;
};

bool cmp1(Stall a,Stall b)
{
    return a.interval > b.interval;
}

bool cmp2(Stall a,Stall b)
{
    return a.num < b.num;
}

bool cmp3(int a,int b)
{
    return a<b; 
}

int main()
{
    //input
    int M,S,C;
    fin>>M >>S >>C;
    vector<Stall>cows;
    int i;
    for(i=0;i<C;i++)
    {
        Stall temp;
        fin>>temp.num;
        cows.push_back(temp);
    }

    //BUG 3:the input is arbitory order of the num
    sort(cows.begin(),cows.end(),cmp2);   

    //compute the interval
    for(i=0;i<C-1;i++)
        cows[i].interval = cows[i+1].num - cows[i].num;

    //sort by the interval
    sort(cows.begin(),cows.end(),cmp1);

    //store M stalls' num where need cutting
    vector<int>number;

    //BUG 2
    if(M == 1)
        number.push_back(0);

    else
    {
        int loop = min(M,C); //BUG 4
        for(i=0;i<loop-1;i++)
        {   
            number.push_back(cows[i].num);
        }
    }

    //sort by the num
    sort(cows.begin(),cows.end(),cmp2);

    //BUG 1
    sort(number.begin(),number.end(),cmp3);

    //greedy algorithm
    int beg = cows[0].num,end = cows[0].num;
    int result = 0,j=0;
    for(i=0;i<C;i++)
    {
        if(cows[i].num == number[j])
        {
            end = cows[i].num;
            result += end - beg + 1;
            beg = cows[i+1].num;
            j++;
        }
        if(j == M-1)
            break;
    }
    end = cows[C-1].num;
    result += end - beg + 1;
    fout<<result <<endl;

    //close files
    fin.close();
    fout.close();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值