[PAT] A1031 Hello World for U

tech2022-09-06  114

(水)

题目大意

用所给字符串按U型输出。n1和n3是左右两条竖线从上到下的字符个数,n2是底部横线从左到右的字符个数。

思路

AC代码

#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<iostream> #include<string> #include<string.h> #define INF 1000000000 #define MAXV 80 using namespace std; int main() { string input; cin >> input; int n = input.size(); int n1 = (n + 2) / 3 < (n - 1) / 2 ? (n + 2) / 3 : (n - 1) / 2; int n2 = n + 2 - 2 * n1; //cout << n1 << n2 << endl; char ans[MAXV][MAXV]; int i, j = 0; for (i = 0;i < n1 - 1;i++) { cout << input[i]; for (j = 0;j < n2 - 2;j++) cout << " "; cout << input[n - i - 1] << endl; } for (i = 0;i < n2;i++) { cout << input[n1 - 1 + i]; } return 0; }

网上其他人的思路: 要求:

n1 == n3n2 >= n1n1为在满足上述条件的情况下的最大值

分析:假设n = 字符串长度 + 2,因为2 * n1 + n2 = n,且要保证n2 >= n1, n1尽可能地大,分类讨论:

如果n % 3 == 0,n正好被3整除,直接n1 == n2 == n3;如果n % 3 == 1,因为n2要比n1大,所以把多出来的那1个给n2如果n % 3 == 2, 就把多出来的那2个给n2 所以得到公式:n1 = n / 3,n2 = n / 3 + n % 3

把它们存储到二维字符数组中,一开始初始化字符数组为空格,然后按照u型填充进去,最后输出这个数组u。

最新回复(0)