4

Question: We are given an array of 2n integers wherein each pair in this array of integers represents the year of birth and the year of death of a dinosaurs respectively. The range of valid years we want to consider is [-100000 to 2005]. For example, if the input was:

-80000 -79950 20 70 22 60 58 65 1950 2004

it would mean that the first dinosaur had a birth year of –80000 and an year of death of –79950 respectively. Similarly the second dinosaur lived from 20 to 70 and so on and so forth.

We would like to know the largest number of dinosaurs that were ever alive at one time. Write a method to compute this, given the above array of 2n integers.

Can anyone suggest the way to find out solution?

Edit tried with this-> rough code

#include<stdio.h>
#include<stdlib.h>
#include <stddef.h>
static void insertion_sort(int *a, const size_t n) {
    size_t i, j;
    int value;
    for (i = 1; i < n; i++) {
        value = a[i];
        for (j = i; j > 0 && value < a[j - 1]; j--) {
            a[j] = a[j - 1];
        }
        a[j] = value;
    }
}


int  main(){
    int arr[10]={-80000,-79950,20,70,22,60,58,65,1950,2004};
    int strt[5],end[5];
    int bal[5];
     int i,j,k,l,m,length;
     l=0;
     m=0;
   for (i=0; i<10; i++){
       //printf("i = %2d arr[i] = %2d\n", i, arr[i]);
       if(i%2==0){
       strt[l]=arr[i];
       l++;
       }else{
       end[m]=arr[i];
       m++;
       }
   }
   insertion_sort(strt, sizeof strt / sizeof strt[0]);
   insertion_sort(end, sizeof end / sizeof end[0]);
   k=sizeof(end)/sizeof(int);
   for(j=0;j<5;j++){
       bal[i]=strt[i]-end[k-1];
       k--;

   }
   length=sizeof bal / sizeof bal[0];
   insertion_sort(bal, sizeof bal / sizeof bal[0]);
   printf("answer is = %2d",bal[length-1]);

}

But output is not as expected. Please tell me what I miss.

4

5 回答 5

14

Consider each dinosaur birth as an open parenthesis and death as a close one. Then sort the parenthesis by date - this will give you chronological order of every event of birth and death. After that pass over the parenthesis sequence and compute the balance (increment on '(' and decrement on ')' ). Track the maximal balance and it will be the answer.

Update:

Sample source in C++.
Input: number of dinosaurs n, then 2n dates of birth and death.
Output: number of maximal quantity of dinos living at the same time

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int n;
    cin >> n;
    vector<pair<int, int> > dinos(2*n); // <date, died/born>
    int i;
    for( i = 0; i < n; ++i )
    {
        cin >> dinos[ 2 * i ].first >> dinos[ 2 * i + 1 ].first;
        dinos[ 2 * i ].second = 1; // born
        dinos[ 2 * i + 1 ].second = 0; // died
    }
    sort( dinos.begin(), dinos.end()); // sorts by date first
    int ans = 0, balance = 0;
    for( i = 0; i < dinos.size(); ++i )
        if( dinos[ i ].second ) // someone's born
        {
            ++balance;
            ans = max( ans, balance ); // check for max
        }
        else
            --balance;
    cout << ans << endl;
    return 0;
}

P.S. I assumed that if two dinos born and died at the same time then they didn't live together. If you want the opposite, just change the values as born=0, died=1.

于 2013-02-01T12:57:25.540 回答
3
Largest number of dinosaurs that were ever alive at one time?

This is sample source code for java.

Input: number of dinosaurs n, n dates of birth and n dates of death.

Output: largest number of dinosaurs that were ever alive at one time

import java.util.Arrays;

public class Dinosaur {

   public static void main(String args[]) {
        int birthAndDeath[] = { -80000, -79950, 20, 70, 22, 60, 58, 65, 1950, 2004};
        System.out.print("Maximum number of dinosaurs that were ever alive at one time: " + new Dinosaur().findMaxdinosaur(birthAndDeath));
    }

   /**
    * Find the Maximum number of dinosaurs that were ever alive at one time.
    * @param years
    * @return maximum number of dinosaurs that were ever alive at one time.
    */
   public int findMaxdinosaur (int[] years) {
        /** For birth array */
        int birthArray[] = new int [years.length/2];

        /** For death array */
        int deathArray[] = new int [years.length/2]; 

        int birthCounter = 0, deathCounter = 0;
        int currentAliveDinos = 0;

        /** Maximum number of dinosaurs that were ever alive at one time. */
        int maxDinos = 0; 

        int position = 0;

        /** To get the birth and death values in different array */
        for(int index = 0; index < years.length; index = index + 2) {
            birthArray[position] = years[index];
            deathArray[position] = years[index + 1];
            position++;
        }       

        /** Sort the birth and death array in ascending order. */
        Arrays.sort(birthArray);
        Arrays.sort(deathArray);

        /** Calculating max number of dinosaurs that were ever alive at one time **/
        while( birthCounter != years.length/2 && deathCounter != years.length/2) {
            if(birthArray[birthCounter] < deathArray[deathCounter]) {
                currentAliveDinos++;
                birthCounter++;
            } else {
                currentAliveDinos--;
                deathCounter++;
            }
            if(maxDinos < currentAliveDinos) {
                maxDinos = currentAliveDinos;
            }
        }
        return maxDinos;
   }
}
于 2013-02-04T19:10:25.170 回答
2

Create a structure called DinosaurEvent and have it store one year- the year when the event occurred and the type of event - birth or death. Implement your own compare function to pass to qsort to first sort according to year and than to event(take into consideration if the deaths happen before births or the other way around i.e. is the range inclusive in either end) Iterate over the array you are given and put all events in a vector. After that sort the vector and process events in turn. Process all events for a given year at the same time(or only births or death depending on the statement) and re-compute the current number of living dinosaurs(for birth increase by one for death decrease by one). Store the maximum value at all times and this will be your answer. Hope that makes sense.

Sorry for giving the whole solution by I could not figure out a way to give you a hint without actually saying it all.

于 2013-02-01T12:55:05.387 回答
2

Here a python scrypt

n=5
birthAndDeath = [-80000, -79950, 20, 70, 22, 60, 58, 65, 1950, 2004]
birth = [] #date of birth of dinos 
death = [] #date of death of dinos

currentAliveDinos=0
maxDinos=0
dateLastBornForMax=0
b = 0
d = 0

#we populate the both arrays for births and deaths
for i in range(0,2*n,2):
    birth.append(birthAndDeath[i])
    death.append(birthAndDeath[i+1])

#don't forget to sort arrays particuliary for death
death.sort()
birth.sort()
print birth
print death

while b!=5 and d!=5:#there are still unborn dino
    if birth[b] < death[d]: # a dino born
        currentAliveDinos = currentAliveDinos + 1
        b = b + 1 
    else: # a dino died
        currentAliveDinos = currentAliveDinos - 1
        d = d + 1       

    if maxDinos < currentAliveDinos:
        maxDinos = currentAliveDinos
        dateLastBornForMax=birth[b-1]

    print currentAliveDinos

print "max dinos = ", maxDinos, " and last dino born in ", dateLastBornForMax, " when max achieved"
于 2013-02-01T15:19:40.510 回答
1
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{

unsigned int n;
cin >> n;
vector<pair<int, int> > dinos(2*n); // <date, died/born>

unsigned int i;
for( i = 0; i < n; ++i )
{
cin >> dinos[ 2 * i ].first >> dinos[ 2 * i + 1 ].first;
dinos[ 2 * i ].second = 1; // born
dinos[ 2 * i + 1 ].second = 0; // died
}

sort( dinos.begin(), dinos.end()); // sorts by date first
int ans = 0, balance = 0;

for( i = 0; i < dinos.size(); ++i ) {
if( dinos[ i ].second ) // someone's born
{
++balance;
ans = max( ans, balance ); // check for max
} else
--balance;
}
cout << ans << endl;
return 0;
}
于 2013-02-02T09:19:10.560 回答