ACM第一次练习—1001B,1008I

本文介绍了一种针对加工木棍机器的优化算法,通过排序和遍历输入的木棍数据,实现对机器调整时间最小化的计算。使用结构体记录木棍属性,并采用自定义比较函数进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:一个加工木棍的机器,如果后面加工的木棍比前面的长且重,则不需要调机器,否则需要一分钟调机器,输入T组测试实例,每组由N跟木棒编写程序,计算并输出每组测试实例所用的最短的调机器的时间。

思路:结构体来记录木棒的长,重和是否被选中;用sort将输入的木棒排序(相同长度轻的在前);利用一个函数实现对每组木棒的遍历,每遍历一遍删去所有可以不用调机器加工的木棒,记录一共遍历的的次数sum,输出(sum-1)。

感想:怎么实现对结构数组的多次遍历是本题的重点。

代码:

#include<iostream>

#include<algorithm>

#include<cstring>

#define SIZE 5000

 

using namespace std;

 

struct sticks{

    int  length;

    int  weight;

    int flag; 

}stick[SIZE];

 

bool cmp(sticks a,sticks b)

{

    if(a.length==b.length) return a.weight<b.weight;

    else if(a.length<b.length)return true;

    else return false;  

}

 

int main()

{

    int  T,n;

    cin>>T;

    for(int  i=0;i<T;i++)

    {

           cin>>n;

           int  j,k;

           int  time =0;

           int  length1;

           int  weight1;

           memset(stick,0,sizeof(stick));

           for(j=0;j<n;j++)

           {

              cin>>stick[j].length>>stick[j].weight;

           }

           sort(&stick[0],&stick[n],cmp);

           stick[0].flag = 1;

           length1=stick[0].length;

           weight1=stick[0].weight;

           time= 1;

           for(j= 1; j < n; j++)

           {

             for(k= j; k < n; k++)

             {

                  if(!stick[k].flag&&stick[k].length>=length1&&stick[k].weight>=weight1)

                 {

                        length1  = stick[k].length;

                        weight1 =stick[k].weight;

                        stick[k].flag = 1;

                  }

             }

             for(k=1;k<n;k++)

             {

                  if(!stick[k].flag)  break;

              }

             j = k;

             if (j== n)   break;

             length1 = stick[j].length;

             weight1= stick[j].weight;

              stick[j].flag= 1;

             time++;

            }

           cout<<time<<endl;

          

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值