活动选择

时间:2012-05-26 12:33:20

标签: c android-activity selection greedy

我的问题是,我们会获得一系列活动及其开始和结束时间,然后我们必须找出我们可以做的最大活动。 这个问题非常普遍,我已经应用了贪婪的方法,但我的代码中出现了运行时分段错误,因此我将其发布在下面。

#include<stdio.h>
typedef struct event
{
    long long int start_time;
    long long int end_time;
    long long int event_number;
}event;

long long int compare(const void *x, const void *y) 
{
    event *e1 = (event *)x, *e2 = (event *)y;
    return (*e1).end_time - (*e2).end_time;
}
/* Given the list of events, our goal is to maximise the number of events we can
   attend. */
int main()
{
int tests;
scanf("%d",&tests);
while(tests--)
{
long long int number_of_events;
//printf("enter no  of activities");
    scanf("%lld",&number_of_events);
    event T[number_of_events];
    long long int iter;
    for(iter=0;iter<number_of_events;iter++)
    {
 //         printf("enter start time and end time of %dth activity",iter);
            scanf("%lld%lld",&T[iter].start_time,&T[iter].end_time);
            T[iter].event_number = iter;
    }
    /* Sort the events according to their respective finish time. */
    qsort(T,number_of_events,sizeof(event),compare);


    long long int events[number_of_events]; // This is used to store the event
                                            // numbers that can be attended.

    long long int possible_events = 0; // To store the number of possible events

    //Taking the first task
    events[possible_events++] = T[0].event_number;
    long long int previous_event = 0;

    /* Select the task if it is compatable with the previously selected task*/
    for(iter=1;iter<number_of_events;iter++)
    {
            if(T[iter].start_time >= T[previous_event].end_time)
            {
                    events[possible_events++] = T[iter].event_number;
                    previous_event = iter;
            }
    }
    //printf("Maximum possible events that can be attended are %d. They   are\n",
    //  possible_events);
    printf("%lld\n",possible_events);
    /*  list of selected activities
    for(iter=0;iter<possible_events;iter++)
    {
            printf("%d\n",events[iter]);
    }*/

}
return 0;
}

请帮助!! Thanx提前!!

1 个答案:

答案 0 :(得分:0)

在最后的迭代中

for(iter=0;iter<possible_events;iter++)

您可能会使events

的大小超过一个

原因是,在possible_events++的先前使用中,您通过possible_events访问元素时,该变量的值将在访问之后变得比以前更大(因为后修复{ {1}}),所以如果你在每次迭代中调用评估,那么在循环结束后++的值将为possible_events

你需要迭代到少一个:

number_of_events+1