Save the dwarfs
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 954 Accepted Submission(s): 294
We want the escaped dwarfs as many as possible. Please write a program to help the dwarfs.
2 20 10 5 5 30 2 20 10 5 5 35
Sample Output
2
1
Hint
For the first case, the tall dwarf can help the other dwarf escape at first. For the second case, only the tall dwarf can escape.
2 1HintFor the first case, the tall dwarf can help the other dwarf escape at first. For the second case, only the tall dwarf can escape.
#include <iostream>
using namespace std;
struct Node{
int a;
int b;
int priority;
bool state;
Node(int a1,int b1,int priority1,bool state1):a(a1),b(b1),priority(priority1),state(state1)
{}
Node()
{
a=b=priority=-1;
state=false;
}
bool operator<(const Node & rhs)
{
if(a<rhs.a)
return true;
if(a>rhs.a)
return false;
if(b<rhs.b)
return true;
else
return false;
}
};
Node data[2000];
int size=0;int H=0;
int partition(Node * p,int start,int end)
{
int a=start,b=end+1;
int middle=start+(end-start)/2;
Node temp=p[middle];
p[middle]=p[start];
p[start]=temp;
while(a<=b)
{
while(p[++a]<temp&&a<end);
while(temp<p[--b]);
if(a<b)
{ Node t=p[a];
p[a]=p[b];
p[b]=t;
}
}
p[start]=p[a];p[a]=temp;return a;
}
void qSort(int start,int end)
{
if(start<end)
{
int t=partition(data,start,end);
qSort(start,t-1);
qSort(t+1,end);
}
}
void BubbleSort()
{
int exchange=size-1;int bound=size-1;
while(exchange!=-1)
{
bound=exchange;
exchange=-1;
for(int i=0;i<bound;++i)
if(data[i]<data[i+1])
{
Node t=data[i+1];
data[i+1]=data[i];
data[i]=t;
exchange=i;
}
}
}
void SetPriority()
{
static int sum;
sum=0;
for(int i=0;i!=size;++i)
{
if(data[i].state==true)
sum+=data[i].a;
}
for(int i=0;i!=size;++i)
{
if(data[i].state)
{
int temp=sum;int num=-1;
if(data[i].b+sum>=H) num=1;
for(int j=size-1;j>=0;--j)
{
if(j!=i&&data[j].state)
{
if(data[i].b+temp-data[j].a>=H)
{
num++;
temp-=data[j].a;
}
else
break;
}
}
data[i].priority=num;
}
}
}
int MinNum()
{
int result=-1;
for(int i=0;i<size;++i)
{
if(data[i].state==true&&data[i].priority>0)
{
result=i;
break;
}
}
for(int i=0;i<size;++i)
if(data[i].state&&data[i].priority>0&&data[i].priority<data[result].priority)
result=i;
else if(data[i].state&&data[i].priority==data[result].priority&&data[i].a<data[result].a)
result=i;
return result;
}
int MaxEscape()
{
//qSort(0,size-1);
BubbleSort();
int result=0;
SetPriority();
while(1)
{
int min=MinNum();
if(min!=-1)
{
data[min].state=false;
result++;
SetPriority();
}
else
break;
}
return result;
}
void main()
{
while(1)
{
int n;
cin>>n;size=n;
while(n-- >0)
{
cin>>data[n].a>>data[n].b;
data[n].state=true;
}
cin>>H;
n=MaxEscape();
cout<<n<<endl;
}
}