【洛谷 for C++】P1598 垂直柱状图

博客介绍了如何使用C++解决洛谷上的P1598问题,采用了一个O(n²)的时间复杂度解法。作者首先统计每个字母的出现次数,找出最频繁的字母,然后按层次逐行输出。文章中提到最初的代码存在未减少最大次数和字符转换的问题,通过修正这些问题完成了解决方案。

原题链接

我的解法

题不难,用了一个O(n²)的解法,首先统计出所有字母出现次数,然后找到其中出现最多的次数,从它开始逐级往下输出,也没遇到什么坑(不过最初写的版本里面没注意到每次输出完一行之后maxNum要 - 1
以及最后不知道该怎么从int转成我需要的char,所以只好另开了一个数组来对应字母orz
贴一下代码

#include <iostream>
#include <string>

const int LEN = 26;
const char LETTER[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

using namespace std;

int main() {
	string s;
	int a[LEN] = { -1 };

	for (int i = 0; i < 4; i++) {
		getline(cin, s);
		for (int i = 0; i < s.length(); i++) {
			int tmp = (int)s[i];
			if (tmp >= 65 && tmp <= 90) {
				if (a[tmp - 65] != -1)
					a[tmp - 65]++;
				else
					a[tmp - 65] = 1;
			}
		}
	}

	//print (pay attention: do not print those -1 ones)
	//1. find the maximun one in the array
	int maxNum = 0;
	for (int i = 0; i < LEN; i++) {
		if (a[i] > maxNum)
			maxNum = a[i];
	}

	for (int i = maxNum; i > 0; i--) {
		for (int j = 0; j < LEN; j++) {
			if (a[j] != -1) {
				if (a[j] == maxNum && j != LEN - 1) {
					cout << "* ";
					a[j]--;
				}
				else if (a[j] == maxNum && j == LEN - 1) {
					cout << "*";
					a[j]--;
				}
				else if (a[j] < maxNum && j != LEN - 1) {
					cout << "  ";
				}
				else if (a[j] < maxNum && j == LEN - 1) {
					cout << " ";
				}

			}
		}
		cout << endl;
		maxNum--;
	}

	//最后输出字母
	for (int i = 0; i < LEN; i++) {
		if (a[i] != -1 && i != LEN - 1) {
			cout << LETTER[i] << " ";
		}
		else if (a[i] != -1 && i == LEN - 1) {
			cout << LETTER[i];
		}
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值