跳到正文

题解

调了一个小时的 UVA10333 The Tower of ASCII

ImmatureDreamer约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年7月14日
收录
2026年7月15日
更新
2026年10月27日
篇幅
约 5 分钟
获赞
1
题目
UVA10333

版本

  1. v1当前

数学部分

这个塔是分成几个部分建的,且有要求尽量多层的前提下,最下面的部分尽量高,且严格递增。那么左边就构造等差数列 1,2,…1,2,\dots 为每层高度,在最后一层补齐剩余高度。

例如 H=12H=12 时从上到下构造为 1,2,3,61,2,3,6。本来构造了等差数列 1,2,3,41,2,3,4 但需要补齐剩余的 22 高度,因此加到最下面一层。

那么就可以处理出每层结束的位置了。又因为右边需要比左边少一层,且也要求最下面的部分尽量高,且严格递增,那么就将左边的最下面两层合并为一层,如 H=12H=12 时从上到下依次 1,2,91,2,9。

实现部分

用变量存当前的前导空格数和中间的填充物数。当遇到左边一层的结束时,下一层的前导空格数量减 22,下一层除其开头的填充物数量加 22,且开头要输出两个 *。注意每行的开头结尾都要输出 #。

说起来简单,写起来就有很多坑了,看代码吧。

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long

int n;


/*
h=5 1,4
h=10 1,2,3,4
h=9 1,2,6
h=8 1,2,5

Triangle number T[i] (1,3,6,10...)
T[i] = 1+2+...+(i-1)+i
T[i]-1 = 1+2+...+(i-1)+(i-1), could not form

Define t[i] = the number of triangle numbers that <=i
The final width = 2(t[n] - 1) + 2(t[n] - 2) + 4 + 2 = 4*t[n]
*/

signed main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	
	int q_idx = 0;
	
	while(cin >> n){
		vector<int> left_sec; // the end of each section
		
//		left_sec.push_back(0);
		
		int now = 0, num;
		for(num = 1; ; ++ num){
			now += num;
			if(now > n) break;
			left_sec.push_back(now);
		}
		-- num;
//		cout << "now=" << now << "\n";
//		cout << "num=" << num << "\n";
		left_sec[left_sec.size() - 1] = n;
//		for(int i : left_sec)
//			cout << i << " ";
//		cout << "\n";
		
		vector<bool> left_tp(n + 1, 0), right_tp(n + 1, 0); // Is this position a turning point?
//		left_tp[1] = right_tp[1] = 1;
		for(int i = 0; i < left_sec.size() - 1; ++ i){
			left_tp[left_sec[i]] = 1;
//			cout << i << " " << left_sec.size() << "\n";
			if(i != left_sec.size() - 2) right_tp[left_sec[i]] = 1;
		}
		
//		cout << "left_tp:\n";
//		for(int i : left_tp) cout << i << " ";
//		cout << "\nright_tp:\n";
//		for(int i : right_tp) cout << i << " ";
		
		cout << "Tower #" << ++ q_idx << "\n";
		
		
		int space_num = 2 * (num - 1), intermediate_num = 4;
		
		for(int i = 1; i <= space_num; ++ i) cout << " ";
		cout << "#****#\n";
		space_num -= 2;
		
		for(int i = 2; i <= n; ++ i){
			for(int j = 1; j <= space_num; ++ j) cout << " "; // leading spaces
			cout << "#"; // left hash sign
			if(left_tp[i]){
				space_num -= 2;
			}
			if(left_tp[i - 1])
				cout << "**";
			for(int j = 1; j <= intermediate_num; ++ j) cout << ".";
			if(right_tp[i - 1]){
				cout << "**";
				intermediate_num += 2;
			}
			if(left_tp[i - 1])
				intermediate_num += 2;
			cout << "#\n";
		}
		
		cout << "\n\n";
	}
	
	return 0;
}

后记

作者写这题当天的运势:

宜:重构代码

代码质量明显提高

这个吧……

原文