I just completed a challenge in Dcoder using C. I got one correct test case out of three, and I can't seem to find the problem that prevents me from getting the other two test cases right as well. I'm still new to C, so please excuse if my code may look inexperienced. Any help is appreciated.
Here is the task:
Problem Statement
Students of Dcoder school love Mathematics. They love to read a variety of Mathematics books. To make sure they remain happy,their Mathematics teacher decided to get more books for them. A student would become happy if there are at least X Mathematics books in the class and not more than Y books because they know "All work and no play makes Jack a dull boy".The teacher wants to buy a minimum number of books to make the maximum number of students happy.Input
The first line of input contains an integer N indicating the number of students in the class. This is followed up by N lines where every line contains two integers X and Y respectively.Output
Output two space-separated integers that denote the minimum number of mathematics books required and the maximum number of happy students. Explanation: The teacher could buy 5 books and keep student 1, 2, 4 and 5 happy.Constraints
1<=N<=10000 1<=X,Y<=10^9Sample Input
5
3 6
1 6
7 11
2 15
5 8Sample Output
5 4
And here is my code:
#include <stdio.h>
//Compiler version gcc 6.3.0
typedef struct{
int minBooks;
int maxBooks;
} Student;
typedef struct{
int books;
int happyStudents;
} Happiness;
void fillarray(Student *arr, int len){
for(int i = 0; i < len; i++){
scanf(" %d", &arr[i].minBooks);
scanf(" %d", &arr[i].maxBooks);
}
}
int getmaximum(Student *arr, int len){
int max = 0;
for(int i = 0; i < len; i++)
if(arr[i].maxBooks > max)
max = arr[i].maxBooks;
return max;
}
Happiness *calchappiness(Student *arr, int len, int max){
Happiness *re = malloc(max * sizeof(Happiness));
for(int i = 1; i <= max; i++){
re[i - 1].books = i;
for(int j = 0; j < len; j++){
if(i >= arr[j].minBooks && i <= arr[j].maxBooks)
re[i - 1].happyStudents++;
}
}
return re;
}
Happiness getmaxhappiness(Happiness *arr, int len){
Happiness re;
re.happyStudents = 0;
for(int i = 0; i < len; i++)
if(arr[i].happyStudents > re.happyStudents)
re = arr[i];
return re;
}
Happiness getminbooks(Happiness *arr, int len){
Happiness re;
re.books = 1000;
for(int i = 0; i < len; i++)
if(arr[i].books < re.books)
re = arr[i];
return re;
}
Happiness besthappiness(Happiness *arr, int len){
Happiness re = getminbooks(arr, len);
for(int i = 0; i < len; i++){
if(arr[i].happyStudents > re.happyStudents)
re = arr[i];
}
return re;
}
int main()
{
int len;
scanf(" %d", &len);
Student *students = malloc(len * sizeof(Student));
fillarray(students, len);
int happylen = getmaximum(students, len);
Happiness *happy = calchappiness(students, len, happylen);
Happiness output = besthappiness(happy, happylen);
printf("%d %d", output.books, output.happyStudents);
free(students);
free(happy);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire