C小加有一些木棒,它们的长度和质量都已经知道,需要一个机器处理这些木棒,机器开启的时候需要耗费一个单位的时间,如果第i+1个木棒的重量和长度都大 于等于第i个处理的木棒,那么将不会耗费时间,否则需要消耗一个单位的时间。因为急着去约会,C小加想在最短的时间内把木棒处理完,你能告诉他应该怎样做 吗?
3 5 4 9 5 2 2 1 3 5 1 4 3 2 2 1 1 2 2 3 1 3 2 2 3 1
2 1 3
先贴下自己的dp超时代码:
#include<stdio.h>
#include<algorithm>
#define MAX(x,y) x>y?x:y
using namespace std;
struct Case{
int L,W;
}strick[5001];
int cmp(Case a,Case b){
if(a.L==b.L)return a.W<b.W;
else return a.L<b.L;
}
int main(){
int T,N,dp[5001],max;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
for(int i=0;i<N;++i){dp[i]=1;
scanf("%d%d",&strick[i].L,&strick[i].W);
}
sort(strick,strick+N,cmp);
max=0;
for(int i=0;i<N;++i){
for(int j=0;j<=i;++j){
if(strick[j].W>strick[i].W)dp[i]=dp[j]+1;
max=MAX(dp[i],max);
}
}
printf("%d\n",max);
}
return 0;
}
借助大神理解解写的代码:
#include<stdio.h>
#include<algorithm>
using namespace std;
struct Case{
int L,W,dis;
};
struct Case stick[5001];
int cmp(Case a,Case b){
if(a.L==b.L)return a.W<b.W;
else return a.L<b.L;
}
int main(){int T,N,t,flot;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
for(int i=0;i<N;++i)scanf("%d%d",&stick[i].L,&stick[i].W),stick[i].dis=1;
sort(stick,stick+N,cmp);flot=0;
for(int i=0;i<N;++i){
if(stick[i].dis==0)continue;
t=stick[i].W;
for(int j=i+1;j<N;++j){
if(stick[j].dis&&t<=stick[j].W)stick[j].dis=0,t=stick[j].W;
}
flot++;
}
printf("%d\n",flot);
}
return 0;
}
/*题解:
结构体排序,一级排木棒的重量,二级排木棒的长度,均由小到大。
进行了多少次外层循环,就是花费的分钟数。
*/
若排序后,如图:
则,花费了2分钟。
原文:http://www.cnblogs.com/handsomecui/p/4553462.html