C语言会场安排问题贪心算法,会场安排问题(贪心算法)

本文介绍了一个C++实现的SQLIST链表结构,重点讲解了insqlist函数的优化,通过减少比较次数提高插入效率,并展示了destroysqlist函数用于销毁链表。代码实例详细解释了如何维护时间区间有序的计划列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include

#include

#include

using namespace std;

typedef struct plan

{

int startime;

int endtime;

struct plan *next;

}sqlist;

void insqlist(sqlist **top,int s,int e)

{

sqlist *p,*tmp=*top,*q;

p=(sqlist *)malloc(sizeof(sqlist));

p->startime=s;

p->endtime=e;

if(tmp==NULL)

{

*top=p;//修改头指针所指地址

p->next=NULL;

}

else

{

for(q=tmp;q!=NULL;q=q->next)

{

if(q->endtime>= e)

{

p->next=q;

*top=p;

break;

}

if(q->endtimenext!=NULL)

{

if(q->endtimenext->endtime>=e)

{

p->next=q->next;

q->next=p;

break;

}

}

else

{

q->next=p;

p->next=NULL;

break;

}

}

}

}

//销毁链表

int destroysqlist(sqlist **p)

{ sqlist *tmp=*p,*tmptmp=NULL;

if(tmp==NULL)

return 0;

while(tmp!=NULL)

{

tmptmp=tmp->next;

free(tmp);

tmp=tmptmp;

}

return 0;

}

int main()

{

int num=0,onetotall=0,begin=0,end=0,total;

cin>>num;

while(num--)

{ sqlist *top=NULL,*tmp=NULL;

cin>>onetotall;

for(int i=0;i

{

cin>>begin;cin>>end;

insqlist(&top,begin,end);

}

// tmp=top;

// while(tmp!=NULL)

// {

// cout<endtime<

// tmp=tmp->next;

// }

tmp=top;

total=1;

int tmpb=tmp->startime,tmpe=tmp->endtime;

tmp=tmp->next;

while(tmp!=NULL)

{

if(tmp->startime>=(tmpe+1))

{

total++;

tmpb=tmp->startime;

tmpe=tmp->endtime;

}

tmp=tmp->next;

}

cout<

destroysqlist(&top);

tmpb=0;tmpe=0;

}

return 0;

}

优化后的代码:

#include

#include

#include

using namespace std;

typedef struct plan

{

int startime;

int endtime;

struct plan *next;

}sqlist;

void insqlist(sqlist **top,int s,int e)

{

sqlist *p,*tmp=*top,*q;

p=(sqlist *)malloc(sizeof(sqlist));

p->startime=s;

p->endtime=e;

if(tmp==NULL)

{

*top=p;

p->next=NULL;

}

else

{

for(q=tmp;q!=NULL;q=q->next)

{

if(q->endtime>= e)

{

p->next=q;

*top=p;

break;

}

else

{

if(q->next!=NULL)

{

if(q->endtime<=e&&q->next->endtime>=e)

{

p->next=q->next;

q->next=p;

break;

}

}

else{

q->next=p;

p->next=NULL;

break;

}

}

}

}

}

int main()

{

int num=0,onetotall=0,begin=0,end=0,total;

cin>>num;

while(num--)

{

sqlist *top=NULL,*tmp=NULL;

cin>>onetotall;

for(int i=0;i

{

cin>>begin;

cin>>end;

insqlist(&top,begin,end);

}

tmp=top;

total=1;

int tmpb=tmp->startime,tmpe=tmp->endtime;

tmp=tmp->next;

while(tmp!=NULL)

{

if(tmp->startime>=(tmpe+1))

{

total++;

tmpb=tmp->startime;

tmpe=tmp->endtime;

}

free(tmp);

tmp=tmp->next;

}

cout<

}

return 0;

}

原题信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值