Detailed explanation of the letter graphics of the Lanqiao Cup

Problem description
Letters can be used to form some beautiful graphics. An example is given below:

ABCDEFG
BABCDEF
CBABCDE
DCBABCD
EDCBABC

This is a graph with 5 rows and 7 columns. Please find out the pattern of this graph and output a graph with n rows and m columns.

Input format
Input one line, which contains two integers n and m, which respectively represent the number of rows and columns of the graphics you want to output.
Output format
Output n lines, each m characters, for your graphics.
Sample input
5 7
sample output
ABCDEFG
BABCDEF
CBABCDE
DCBABCD
EDCBABC
Data scale and convention
1 <= n, m <= 26.

Looking at this topic, for 26 English letters, we apply for an array size of 27 character space, and store it in (I start with arry[1] for easy use), (lazy way). First of all, you can think of the need for two layers of loops to control the output. Observe the title. The first letter of each line is in order, and the position of the first letter in the character array is the number of lines.
Then observe that there is only the first line starting from A, and the rest of the lines are first close to A, and then away from A. Give an intermediate variable to decide whether to close to A or away. Look at the code.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	char arry[27];
	int i,j,k=1;
	char flag = 65;   //字符A的ascii码
	for (i = 1; i <= 26; i++)
	{
    
    
		arry[i] = flag++;       //字符数组赋值
	}
	int m, n;     //行 列 
	int num=0;              //记录输出列数
	int temp;              //记录输出首字母下标  
	cin >> m >> n;
	for (i = 1; i <= m; i++)   //控制行输出
	{
    
    
		temp = i;            //第几行首字母就是第几个字母
		k = 1;              
		num = 0;
		while (temp != 1&&num<n)    
		//第n行,首字母就输出第几个,然后慢慢靠近A,也就是下标temp--,
		//但是要保证列数的准确,假如是4行2列,temp--之后第四行应该是DCBA,
		//但我们只需要两列,所以 num<n 保证列数正确。
		{
    
    
			cout << arry[temp--];
			num++;            //记录列数
		}
		while(num<n)    //同上解法  保证列数
		{
    
    
			//上面的while循环是靠近A输出,这段代码是远离A的输出
			//下标k初始化为1,远离A就很好办,k++就好。
			cout << arry[k++];  
			num++;             //记录列数
		}
		cout << endl;
	}
}

In my opinion, what I wrote is fairly detailed, a c/v-only rookie, time is running out, so I’ll just write it here, I wish you all the best in the Blue Bridge Cup! !
If you find a mistake, or better optimize it, you can comment on private messages!! Accept all guidance with an humility.

Guess you like

Origin blog.csdn.net/weixin_43420303/article/details/108791323