C语言中贪婪算法的两个问题:智能冲浪和摘花生

都是用C++写的,不建议只用纯C语言。

# include & ltiostream & gt

# include & ltfstream & gt

# include & lt算法& gt

使用命名空间std

结构谜语{

int时间;

int money

};

结构gt{

布尔算子()(谜语& ampopl,谜语& ampopr){

return opl.money & gtopr.money

}

};

int main()

{

int m,n;

ifstream fin(" riddle . in ");

fin & gt& gtm & gt& gtn;

谜语*谜语=新谜语[n];

for(int I = 0;我& ltn;++i) {

fin & gt& gt谜语[我]。时间;

}

for(int I = 0;我& ltn;++i) {

fin & gt& gt谜语[我]。钱;

}

sort(谜语,谜语+n,gt());

int * rid order = new int[n];

for(int I = 0;我& ltn;++i) {

rid order[I]= 0;

}

for(int I = 0;我& ltn;++i) {

int j;

for(j =谜语[i]。时间-1;j & gt= 0 & amp& ampridorder[j]!=0;- j) {}

if(j & gt;= 0)ridorder[j]= 1;

else m -=谜语[i]。钱;

}

cout & lt& ltm & lt& ltendl

}

# include & ltiostream & gt

# include & ltcstdio & gt

# include & ltcstdlib & gt

# include & ltcstring & gt

# include & ltcmath & gt

# include & lt算法& gt

使用命名空间std

#定义最大数量55

结构花生

{

int x,y,num

}花生[maxn * maxn];

int n,m,t,pcount

布尔运算符& lt(const Peanut & amp一、const花生& ampb)

{

返回a.num & gtb.num

}

无效输入()

{

pcount = 0;

scanf("%d%d%d ",& ampn & amp;m & amp;t);

for(int I = 0;我& ltn;i++)

for(int j = 0;j & ltm;j++)

{

int a;

scanf("%d ",& ampa);

如果(a)

{

花生[pcount]。x = I+1;

花生[pcount]。y = j+1;

花生[pcount]。num = a;

pcount++;

}

}

}

无效工作()

{

int nowtime = peanut[0]。x+1;

if (nowtime + peanut[0])。x & gtt)

{

printf(" 0 \ n ");

返回;

}

int ans = peanut[0]。num

for(int I = 1;我& ltpcounti++)

{

nowtime += abs(peanut[i]。x - peanut[i - 1]。x) + abs(花生[i]。y型花生[i - 1]。y)+1;

if (nowtime + peanut[i]。x & gtt)

打破;

ans += peanut[i]。num

}

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

}

int main()

{

//freopen("t.txt "," r ",stdin);

int t;

scanf("%d ",& ampt);

while (t -)

{

input();

sort(peanut,peanut+pcount);

work();

}

返回0;

}