您的位置:首页 > 其它

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

2016-03-22 21:49 344 查看
题意:一个加工木棍的机器,如果后面加工的木棍比前面的长且重,则不需要调机器,否则需要一分钟调机器,输入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
,cmp);


           stick[0].flag = 1;

           length1=stick[0].le
bbb7
ngth;


           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;

          

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: