一.貪心算法1
問題描述
假設要在足夠多的會場裏安排一批活動,並希望使用儘可能少的會場.設計一個有效的貪心算法進行安排(這個問題實際上是著名的圖着色問題,若將每一個活動作爲圖的一個頂點,不相容活動間用邊相連,使相鄰頂點着有不同顏色的最小着色數,相應於要找的最小會場數) .
算法思想
把所有活動的開始時間和結束時間按從小到大的順序排列,依次遍歷,當遇到開始時間時,count++,當遇到結束時間時,count–,最後,count的最大值就是安排這些活動所需要的最小會場數.
ps(說一下我的理解):當遇到開始時間時,爲其分配一個會場舉行活動,因爲開始的時間一定比結束的時間早,當我遇到一個結束時間時,說明這個活動已經結束,這個會場現在已經空閒,count–,我可以用這個會場去安排別的活動,所以,count的最大值就是我所需的安排這些所有活動所需要的最小的會場數.
代碼如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Time
{
int t; //活動開始的時間或結束的時間
bool f; //標記這個活動是開始時間還是結束時間
};
int greedy(vector<Time> x)
{
int max=0,cur=0,n=x.size();
sort(x.begin(),x.end(),[](const Time &a,const Time &b){return a.t < b.t;}); //混排
for(int i=0;i<n-1;i++)
{
if(x[i].f)
cur++;
else
cur--;
/*處理x[i]=x[i+1]的情況,當cur>max且x[i]=x[i+1]時,i時間肯定是開始時間,i+1時間可能是開始時間,也可能是結束時間,如果是結束時間,說明某活動開始時間和結束時間相同,不需要會場,故不對max更新,如果是開始時間,那在i+1更新max效果一樣,這樣就避免了開始時間和結束時間相同時,仍然爲其分配了會場. */
if(x[i].t<x[i+1].t && cur>max){
max=cur;
}
}
return max;
}
int main()
{
vector<Time> x;
int n,i;
Time temp;
while(cin>>n,n)
{
for(i=0;i<n;i++)
{
temp.f=true;
cin>>temp.t;
x.push_back(temp);
temp.f=false;
cin>>temp.t;
x.push_back(temp);
}
cout<<greedy(x)<<endl;
x.clear();
}
return 0;
}
二.貪心算法2
問題描述如上.
* 首先,選擇一個會場,遍歷所有的活動,把能放在一個會場的活動放在一個會場裏(在一個會場裏安排儘可能多的活動).
* .重新選擇一個會場,遍歷所有沒有被安排的活動,把相容的活動放在這個會場中.
* 重複第二步,直到所有的活動都被安排.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include<vector>
//在一個會場裏安排儘可能多的活動
using namespace std;
struct Activity_Info
{
int s; //開始時間
int e; //結束時間
bool f; //標記是否被添加過
};
int ArrangingActivities(vector<Activity_Info> acts)
{
//按結束時間從小到大排序
sort(acts.begin(),acts.end(),[](const Activity_Info &a,const Activity_Info &b){return a.e < b.e;});
int count = 0;
int currTime = -1; //當前時間
int i,flag=acts.size(),t=0;
while(flag){
count=0;
currTime=-1;
for (i = 0; i < acts.size(); i++){
if (acts[i].s > currTime && acts[i].f)
{
count++;
currTime = acts[i].e;
acts[i].f=false;
flag--;
}
}
t++;
}
return t;
}
int main(void)
{
int ncases;
cin >> ncases;
vector<Activity_Info> acts;
int i,n;
Activity_Info temp;
while (ncases-- != 0)
{
cin >> n;
for (i = 0; i < n; i++)
{
cin >> temp.s >> temp.e;
temp.f=true;
acts.push_back(temp);
}
cout << ArrangingActivities(acts)<<endl;
}
return 0;
}