Venue arrangement problem (greedy algorithm)

Venue arrangement problem (greedy algorithm)

1. Title description
Suppose that a group of events should be arranged in enough venues and hope to use as few venues as possible. Design an effective greedy algorithm to arrange. For the given k events to be scheduled, calculate the timetable with the least venue.
Input
There is a positive integer k in the first line, which means that there are k activities to be arranged. In the next k rows, each row has 2 positive integers, representing the start time and end time of the k activities to be scheduled. The time is in minutes from 0:00.
Output Output
the calculated minimum number of conference sites to.
Sample input Copy
5
1 23
12 28
25 35
27 80
36 50
Sample output Copy
3

2. Case analysis In
this case, a structure is used to define an event, count represents the number of events, room_avail can arrange the free time period, room_num represents the number of scheduled venues, flag is used as the event tag, and the scheduled event flag is set to 1. . Through the greedy algorithm, the local optimal solution is selected, that is, enough activities are arranged in the least venue, and when other activities cannot be arranged in one venue, it will be arranged to the next venue until all the activities are arranged. Return to the final The number of venues where all events are scheduled.

Insert picture description here
Three, case code

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

struct ans{   //定义结构体表示活动 
	int begin,end;
	bool flag; //设置标志 
};

int arrange(int k,ans *a)
{
int count=k,room_avail=0,room_num=0;
while(count>0)
  {
	for(int i=1;i<=k;i++)
	{
		if((a[i].begin>room_avail)&&(a[i].flag==0))  //如果当前活动未安排并且和会场已有活动不冲突 
		{
			room_avail=a[i].end;  //将当前活动加入该会场并更新会场的空闲时间
			a[i].flag=1;
			count--; 
		}
	}
	room_avail=0;  //将room_avail初始化
	room_num++;   //遍历一次,使用的会场数加一 
  } 
	return room_num; //返回安排的会场数 
	
}
int main()
{
int k,room_num;
cin>>k;
ans a[k+1];
for(int i=1;i<=k;i++)
{
	cin>>a[i].begin>>a[i].end;
	a[i].flag=0;
}

room_num=arrange(k,a) ;
cout<<room_num<<endl;
return 0;
}

Four, running results

5
1 23
12 28
25 35
27 80
36 50
3

--------------------------------
Process exited after 1.365 seconds with return value 0
请按任意键继续. . .






Guess you like

Origin blog.csdn.net/weixin_43553142/article/details/103571130