Algorithm Gossip (21) 最大訪客數

前言

This Series aritcles are all based on the book 《經典算法大全》; 對於該書的所有案例進行一個探究和拓展,並且用python和C++進行實現; 目的是熟悉常用算法過程中的技巧和邏輯拓展。

提出問題

21.Algorithm Gossip: 最大訪客數

說明

現將舉行一個餐會,讓訪客事先填寫到達時間與離開時間,爲了掌握座位的數目,必須先估計不同時間的最大訪客數。

解法

這個題目看似有些複雜,其實相當簡單,單就計算訪客數這個目的,同時考慮同一訪客的來訪時間與離開時間,反而會使程式變得複雜;只要將來訪時間與離開時間分開處理就可以了;
假設訪客 i 的來訪時間爲x[i],而離開時間爲y[i]。
在資料輸入完畢之後,將x[i]與y[i]分別進行排序(由小到大),道理很簡單,只要先計算某時之前總共來訪了多少訪客,然後再減去某時之前的離開訪客,就可以輕易的解出這個問題。

分析和解釋

上面思路已經很清晰, 按部就班實現功能即可。

代碼

C實現

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
#define SWAP(x,y) {int t; t = x; x = y; y = t;}
int partition(int[], int, int);
void quicksort(int[],int,int);
int maxguest(int[], int[], int,int);
int main(void) {
    int x[MAX] = {0};
    int y[MAX] = {0};
    int time = 0;
    int count = 0;
    printf("\input the come and leave 125; time (0~24):");
    printf("\n example:10 15");
    printf("\ninput -1 -1END");
    while(count < MAX){
        printf("\n>>");
        scanf("%d %d", &x[count],&y[count]);
        if(x[count] < 0)
            break;
        count++;
        }
    if(count >= MAX){
        printf("\n out of the max visitor (%d)", MAX);
        count--;
        }

    quicksort(x, 0, count);
    quicksort(y, 0, count);
    while(time < 25){
        printf("\n the time of %d max visitor:%d",
        time, maxguest(x, y, count,time));
        time++;
        }
    printf("\n");
    return 0;
    }
int maxguest(int x[],int y[], int count,int time) {
    int i, num = 0;
    for(i = 0; i <= count;i++){
        if(time > x[i])
            num++;
        if(time > y[i])
            num--;
        }
    return num;
    }
int partition(int number[], intleft, int right){
    int i, j, s;
    s = number[right];
    i = left - 1;
    for(j = left;j < right;j++) {
        if(number[j] <= s) {
            i++;
            SWAP(number[i],number[j]);
            }
        }
    SWAP(number[i+1],number[right]);
    return i+1;
    }
void quicksort(intnumber[], int left, int right){
    int q;
    if(left < right){
        q = partition(number,left, right);
        quicksort(number,left,q-1);
        quicksort(number,q+1,right);
        }
    }


拓展和關聯

後記

參考書籍

  • 《經典算法大全》
  • 維基百科
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章