safe or unsafe

链接

这题要求我们对WPL(带全路径长度)进行计算,而WPL就等于每个子节点相加后形成的加权节点的总和,比如有四组数据出现的频率分别是1 2 3 4

那么加权节点的值分别为1+2=3,3+3=6,6+4=10,总和为19

直接计算WPL=3x(1+2)+2x3+1x4=19

二者相等,依据这个就好处理了

考虑使用map统计频率,用优先队列来进行计算

#include<bits/stdc++.h>
using namespace std;
int main() {
	int n;cin >> n;
	for (int i = 0;i < n;i++) {
		int setWPL;
		int WPL = 0;
		cin >> setWPL;
		string str;
		cin >> str;
		map<char, int>freq;
		for (char ch : str) {
			freq[ch]++;
		}
		priority_queue<int,vector<int>,greater<int>> tree;
		for (const auto& it : freq) {
			tree.push(it.second);
		}
		if (tree.size() == 1) {
			WPL = tree.top();
		}
		while (tree.size()>1) {
			int a, b;
		
			a= tree.top();
			tree.pop();
			b= tree.top();
			tree.pop();
			tree.push(a + b);
			WPL += (a + b);
		}
		
		if (WPL <= setWPL) {
			cout << "yes" << endl;
		}
		else {
			cout << "no" << endl;
		}

	}
}

时间复杂度:O(n)

空间复杂度:O(n时间复杂度:O(n × (m + k log k))

n:测试用例数量

m:每个字符串长度

k:字符串中不同字符数量

空间复杂度:O(m + k)

全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 15:05
已编辑
快手 前端工程师 28*16+2*12 大专
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-20 23:32
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务