HDU 1873 看病排队(优先队列)

本文探讨了C语言中变量的生命周期问题,并通过一个具体的编程实例演示了如何利用优先队列解决实际问题。文章重点介绍了如何合理地放置变量以避免手动清理资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此题水题,价值不大。写这个题解,是想回顾一个问题:变量的生命周期问题,C语言基础中的基础......


#include <cstdio>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <queue>
using namespace std;
struct node {
	int index, prior;
	node(int a, int b) :index(a), prior(b) {}
	bool operator<(const node &a)const{
		if (this->prior != a.prior) {
			return this->prior < a.prior;
		}
		else {
			return this->index > a.index;
		}
	}
};
int main() {
	int a, b, k, n;
	string s;
	while (scanf("%d", &n) != EOF) {
		priority_queue<node> doc[4];//while和for体内的变量,一次循环就释放内存空间 所以这里把优先队列放到while体内,每次循环都是新的,是不用自己清空队列的
		k = 0;
		for (int i = 0; i < n; i++) {
			cin >> s;
			if (s[0] == 'I') {
				cin >> a >> b;
				doc[a].push(node(++k, b));
			}
			else {
				cin >> a;
				if (doc[a].empty()){
					cout << "EMPTY" << endl;
				}
				else{
					node te = doc[a].top();
					doc[a].pop();
					cout << te.index << endl;
				}
			}
		}
	}
	return 0;
}

要是脑子短路,可能会想,三个优先队列要放到哪里呢,放错了,每个样例结束,还要自己清空队列。其实稍微回顾下C语言基础可知,放到while/for循环体内,while/for循环体内的变量,每次循环后会释放内存。

样例:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
class A{
public:
	A(){
		cout << "build" << endl;
	}
	~A(){
		cout <<"erase" << endl;
	}
};
int main(){
	int count = 3;
	while(count--){
		A a;
		cout<<"in"<<endl;
	}
	return 0;
}
运行结果:

build

in

erase

build

in

erase

build

in

erase

证明了上述观点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值