Wooden Sticks
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 16395 Accepted Submission(s): 6731
(a) The setup time for the first wooden stick is 1 minute.
(b) Right after processing a stick of length l and weight w , the machine will need no setup time for a stick of length l' and weight w' if l<=l' and w<=w'. Otherwise, it will need 1 minute for setup.
You are to find the minimum setup time to process a given pile of n wooden sticks. For example, if you have five sticks whose pairs of length and weight are (4,9), (5,2), (2,1), (3,5), and (1,4), then the minimum setup time should be 2 minutes since there is a sequence of pairs (1,4), (3,5), (4,9), (2,1), (5,2).
題意:機器處理木材,每次開始時需要1分鐘的設置是時間,如果下一根木棒的長度和重量都大於或等於上一根木棒,呢麼就不用去設置,請問怎樣設置才能使化肥設置及其的時間最短。
這是剛學貪心算法,按照書上的運行了一遍,弄懂了
思路:將木棒進行自定義排序,長度小,重量輕的排在前邊,然後每次從後邊的比較,然後算出來最小時間!
代碼如下“:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAXN 5005
using namespace std;
struct Node
{
int length,weight;
bool flag; // flag用來標記這根木棒是否處理過
};
bool cmp(Node a,Node b)
{
return a.length<=b.length || (a.length==b.length && a.weight<=b.weight); //自定義排序,長度小,質量輕的排在前邊
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
Node node[MAXN];
int n,cot=0,k;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d%d",&node[i].length,&node[i].weight);
node[i].flag=false;
}
sort(node,node+n,cmp); //自定義排序,當然有些條件不滿足的,可以輸出看一下
for(int i=0;i<n;i++)
{
if(node[i].flag) continue; //如果這跟木棒處理過,直接進行下一個循環,知道找到新的未處理的木棒
cot++;k=i; //這時候,花費的時間+1
for(int j=i+1;j<n;j++)
{
if(node[j].length>=node[k].length && node[j].weight>=node[k].weight && node[j].flag==false) // 如果這跟木棒長度,質量都大於上一根而且沒有處理過
{
node[j].flag=true; //處理這一跟木棒
k=j;//更新一下,把這一跟作爲下一次的對比,看下一根木棒的長度,質量是否滿足條件
}
}
}
printf("%d\n",cot);
}
return 0;
}
總結:貪心,每次要看出能貪心的對象,才能去做