C++ STL priority_queue代码笔记

一种细胞在诞生(即上次分裂)后会在500到2000秒内分裂为两个细胞,每个细胞又按照同样的规律继续分裂。 

#include <iostream>
#include <ctime>
#include <queue> 
using namespace std;

const int SPLIT_TIME_MIN = 500;        //细胞分裂最短时间
const int SPLIT_TIME_MAX = 2000;       //细胞分裂最长时间

class Cell;
priority_queue<Cell> cellQueue;

class Cell {    //细胞类
private:
	static int count;   //细胞总数
	int id;             //当前细胞编号
	int time;           //细胞分裂时间
public:
	Cell(int birth) : id(count++) { //birth为细胞诞生时间
		//初始化,确定细胞分裂时间
		time = birth + (rand() % (SPLIT_TIME_MAX - SPLIT_TIME_MIN)) + SPLIT_TIME_MIN;
	}
	int getId() const { return id; }            //得到细胞编号
	int getSplitTime() const { return time; }   //得到细胞分裂时间
	bool operator < (const Cell& s) const       //定义“<”
	{
		return time > s.time;
	}
	void split() const{  //细胞分裂
		Cell child1(time), child2(time);    //建立两个子细胞
		cout << time << "s: Cell #" << id << " splits to #"
			<< child1.getId() << " and #" << child2.getId() << endl;
		cellQueue.push(child1);   //将第一个子细胞压入优先级队列
		cellQueue.push(child2);   //将第二个子细胞压入优先级队列
	}
};
int Cell::count = 0;
int main() {
	srand(static_cast<unsigned>(time(0)));
	int t;                          //模拟时间长度
	cout << "Simulation time: ";
	cin >> t;
	cellQueue.push(Cell(0));        //将第一个细胞压入优先级队列
	while (cellQueue.top().getSplitTime() <= t) {
		cellQueue.top().split();    //模拟下一个细胞的分裂
		cellQueue.pop();            //将刚刚分裂的细胞弹出
	}
	return 0;
}

输出结果:

Simulation time: 5000
535s: Cell #0 splits to #1 and #2
1430s: Cell #2 splits to #3 and #4
1468s: Cell #1 splits to #5 and #6
2058s: Cell #4 splits to #7 and #8
2653s: Cell #6 splits to #9 and #10
2774s: Cell #3 splits to #11 and #12
2800s: Cell #8 splits to #13 and #14
3226s: Cell #5 splits to #15 and #16
3326s: Cell #7 splits to #17 and #18
3376s: Cell #9 splits to #19 and #20
3624s: Cell #13 splits to #21 and #22
3860s: Cell #16 splits to #23 and #24
3910s: Cell #20 splits to #25 and #26
3925s: Cell #19 splits to #27 and #28
3996s: Cell #11 splits to #29 and #30
4199s: Cell #10 splits to #31 and #32
4229s: Cell #14 splits to #33 and #34
4468s: Cell #12 splits to #35 and #36
4536s: Cell #28 splits to #37 and #38
4536s: Cell #29 splits to #39 and #40
4582s: Cell #17 splits to #41 and #42
4760s: Cell #18 splits to #43 and #44
4842s: Cell #23 splits to #45 and #46
4957s: Cell #22 splits to #47 and #48
5000s: Cell #15 splits to #49 and #50

猜你喜欢

转载自blog.csdn.net/qq_37592750/article/details/83480438