# Section 1.3 Barn Reapir

101人阅读 评论(0)

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;
}
0
0

个人资料
• 访问：3096次
• 积分：173
• 等级：
• 排名：千里之外
• 原创：14篇
• 转载：0篇
• 译文：1篇
• 评论：0条
阅读排行