Monday, December 9, 2013

codechef COOLING - Cooling Pies solution

problem: http://www.codechef.com/problems/COOLING/

editorial: http://discuss.codechef.com/questions/4211/cooling-editorial

EXPLANATION

The following greedy algorithm always finds the optimum answer:
  • Choose the lightest pie not yet on a rack
  • If none of the remaining racks can hold this pie, stop
  • Of all the racks that can hold this pie, place the pie on the rack with the smallest weight limit
  • If there are no more pies, stop. Otherwise, go back to step 1

my (copied) c++ solution to codechef COOLING - Cooling Pies: http://ideone.com/cQAzcX

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
// your code goes here
int a, b, i, j, weigh[35], limt[35], count;
cin>>a;
while(a--) {
cin>>b;
count=0;
for(i=0; i<b; i++) cin>>weigh[i];
for(j=0; j<b; j++) cin>>limt[j];
std::stable_sort(weigh, weigh+b);
std::stable_sort(limt, limt+b);
for(i=0, j=0; i<b && j<b; i++) {
while(j<b && weigh[i]>limt[j]) {
j++;
}
if(j<b) {
count++; j++;
}
}
cout<<count<<endl;
}
return 0;
}

NOTE: in my opinion, it would be nice if you count++ inversely. assume weight is X, and limit is Y func respectively. we have(or reach) our desired count++ when Y's element is bigger than or equal to X's particular element. and in that condition we count++. otherwise, we just pass onto Y's next element, till we meet the condition.

No comments:

Post a Comment