Wednesday, June 25, 2014

SPOJ Problem BUSYMAN


I AM VERY BUSY

Explanation:

A basic activity selection problem which uses Greedy approach. The implementation mentioned here states to sort the activities in the increasing order of their finishing times. Initially, we choose the first activity. Now, starting from second activity, current activity can be selected if the finish time of previous selected activity is less than or equal to the starting time of current activity.

Solution:

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

struct act{
    int starting, ending;
}arr[100000];

bool compare(act a, act b){
    if(a.ending < b.ending)
        return true;
    if(a.ending == b.ending)
        return (a.starting < b.starting);
    return false;
}

int main(){
    int t, n, cnt, prevendtime;
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        for(int i=0;i<n;i++)
            scanf("%d%d", &arr[i].starting, &arr[i].ending);
        sort(arr, arr + n, compare);
        cnt = 1;
        prevendtime = arr[0].ending;
        for(int i=1;i<n;i++){
            if(prevendtime <= arr[i].starting){
                cnt++;
                prevendtime = arr[i].ending;
            }
        }
        printf("%d\n", cnt);
    }
}

Any suggestions are welcome.

3 comments:

  1. how did you proved that it z the correct soln?????

    ReplyDelete
  2. Replies
    1. Gives me an AC when I submit. Can you please test your code with test cases at http://spojtoolkit.com/test/BUSYMAN

      Delete

SPOJ Problem ONEZERO

Ones and zeros Explanation: A very good problem to practice BFS skills. I think that much hint is good to give the problem a shot. An...