[算法題] 安排會議室——貪心算法的應用


題目描述

[題目描述]

在大公司里,會議是很多的,開會得有場子,要場子你得先在電子流里預訂。
如果你是項目組新來的小弟,那么恭喜你,每天搶訂會議室的任務就光榮的分給你了。
老大要求你盡可能多的訂會議室,但是這些會議室之間不能有時間沖突。

[Input]
input文件中可以包括多個測試案例。
T(T ≤ 20),輸入文件的第一行表示文件中有多少個測試案例。
N(1 ≤ N ≤ 500),每個測試案例的第一行表示會議室的數目。
每個測試案例中,除第一行以外表示各個會議室的信息。每行會有3個數字,分別表示會議編號、會議起始時間、會議結束時間。


[Output]
輸出可以安排的最大會議數目

[I/O Example]
Input
2
6
1 1 10
2 5 6
3 13 15
4 14 17
5 8 14
6 3 12
15
1 4 8
2 2 5
3 2 6
4 4 6
5 2 3
6 1 6
7 4 7
8 3 5
9 3 8
10 1 2
11 1 7
12 2 4
13 5 6
14 4 5
15 7 8

Output
3
5

 

練習模板

#include <cstdio>
#include <iostream>

using  namespace std;

int main( int argc,  char** argv)
{
     int tc, T;
    cin >> T;
     for(tc =  0; tc < T; tc++)
    {
         // TO DO here
    }

     return  0; // Your program should return 0 on normal termination.
}

 

代碼實現

題目中要求會議時間不可以沖突,所以可以利用貪心算法,盡可能的選擇會議時間結束較早的會議室,這樣就能安排最多的會議室。

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>

using  namespace std;


class MeetingRoom {
public:
     int index;
     int start;
     int end;
public:
    MeetingRoom( int i,  int s,  int e) : index(i), start(s), end(e) {}
};

bool isEndEarly( const MeetingRoom r1,  const MeetingRoom r2) {
     return (r1.end < r2.end);
}

int main( int argc,  char** argv)
{
     int tc, T;
     int num =  0;
     int count =  0;
     int index =  0;
     int start =  0;
     int end =  0;
    vector<MeetingRoom> rooms;

    freopen( " input.txt "" r ", stdin);
    cin >> T;
     for(tc =  0; tc < T; tc++)
    {
        rooms.clear();  //  clear vector

        
//  get all the info of rooms
        cin >> num;
         for ( int i =  0; i < num; i++) {
            cin >> index >> start >> end;
            MeetingRoom room(index, start, end);
            rooms.push_back(room);
        }

         //  sort rooms for end time
        sort(rooms.begin(), rooms.end(), isEndEarly);

         //  use greedy algorithm to solve promblem
        count =  1;
        MeetingRoom prev = rooms[ 0];
         for (vector<MeetingRoom>::iterator it = rooms.begin() +  1; it != rooms.end(); it++) {
            MeetingRoom current = *it;
             if (current.start >= prev.end) {
                count++;
                prev = current;
            }
        }

        cout << count << endl;
    }

     return  0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM