題目來源:http://acm.nyist.net/JudgeOnline/problem.php?pid=236
心急的C小加
- 描述
-
C小加有一些木棒,它們的長度和質量都已經知道,需要一個機器處理這些木棒,機器開啓的時候需要耗費一個單位的時間,如果第i+1個木棒的重量和長度都大於等於第i個處理的木棒,那麼將不會耗費時間,否則需要消耗一個單位的時間。因爲急着去約會,C小加想在最短的時間內把木棒處理完,你能告訴他應該怎樣做嗎?
這題也不是很難 同樣的二級排序 ,然後循環遍歷數組,由於已經排好 L 升序,所以發現 W小於上一個木棒的時候就以這個木棒爲起始,查找能滿足它的條件的木棒,然後標記。
# include <stdio.h>
# include <algorithm>
using namespace std;
struct wood{
int l, w;
int flag;
} woodArray[5005];
int cmp(wood a, wood b)
{
return a.l < b.l || a.l == b.l && a.w < b.w;
}
int main()
{
int T, N, count, last, lastJ, i, j;
freopen("in.txt","r",stdin);
scanf("%d", &T);
while(T--){
scanf("%d", &N);
for(i = 0; i < N; i++){
scanf("%d %d", &woodArray[i].l, &woodArray[i].w);
woodArray[i].flag = 0;
}
sort(woodArray, woodArray + N, cmp);
count = last = lastJ = 0;
for(i = last; i < N; i++){
//flag=1爲已經處理的木頭,跳過
if(woodArray[i].flag) continue;
//上一次循環沒有處理的第一個木頭,就是需要重新設置機器的木頭,從它開始,標記所有滿足它這個條件的木頭
count++;
last = lastJ = i;
for(j = i + 1; j < N; j++){
if(woodArray[j].w >= woodArray[lastJ].w && woodArray[j].flag == 0){
woodArray[j].flag = 1;
lastJ = j;
}
}
}
printf("%d\n", count);
}
return 0;
}
遺憾的是用的時間太多了,1000ms的限制 我花了768ms,嘗試用一次遍歷做,但是有些情況不能滿足,通不過。再試試吧,如果改出來了再貼上來