[C/C++ 演算法]- 最大訪客數
剛才找資料時發現一個C/C++的教學網站,趕快發揮(C/P)的長才將它備份來,有需要的同好,歡迎來(C/P)一下^^。
拷貝來源:
http://openhome.cc/Gossip/AlgorithmGossip/
http://openhome.cc/Gossip/AlgorithmGossip/MaxGuest.htm
#include <stdio.h> #include <stdlib.h> #include <time.h>
#define GUESTS 30
int compare(const void*, const void*); int max(int[][GUESTS], int, int);
int main(void) { srand(time(NULL)); int visits[2][GUESTS] = {0}; int i; for(i = 0; i < GUESTS; i++) { visits[0][i] = (double) rand() / RAND_MAX * 24; visits[1][i] = (double) rand() / RAND_MAX * (24 - visits[0][i]) + visits[0][i]; }
// 預先排序 qsort(visits[0], GUESTS, sizeof(int), compare); qsort(visits[1], GUESTS, sizeof(int), compare);
int t; for(t = 0; t < 24; t++) { int num = max(visits, GUESTS, t); if(num != 0) { printf("%2d 時訪客數:%2d 位\n", t, num); } } return 0; }
int compare(const void* a, const void* b) { return *(int*)a - *(int*)b; }
int max(int visits[][GUESTS], int count, int time) { int num, i; for(num = 0, i = 0; i <= count; i++) { num = time > visits[0][i] ? num + 1 : num; num = time > visits[1][i] ? num - 1 : num; } return num; }
|
沒有留言:
張貼留言