1007[To and Fro]

Description

Mo and Larry have devised a way of encrypting messages. They first decide secretly on the number of columns and write the message (letters only) down the columns, padding with extra random letters so as to make a rectangular array of letters. For example, if the message is "There's no place like home on a snowy night" and there are five columns, Mo would write down t o i o y h p k n n e l e a i r a h s g e c o n h s e m o t n l e w x Note that Mo includes only letters and writes them all in lower case. In this example, Mo used the character `x' to pad the message out to make a rectangle, although he could have used any letter. Mo then sends the message to Larry by writing the letters in each row, alternating left-to-right and right-to-left. So, the above would be encrypted as toioynnkpheleaigshareconhtomesnlewx Your job is to recover for Larry the original message (along with any extra padding letters) from the encrypted one.

*****************************************************************

根据例子来理解

假如确定n为5,字符串的长度为34,那么将是写成5列7行的矩阵形式,最后补上的字符是任意字符,例如‘x’,这里不用考虑这个。注意,这个书写是按竖直顺序的。
举个简单的例子,假设n为5,明文为 theresnoplacelikehomeonasnowynight ,共有34个字符,那么先写成以下形式
t o i o y
h p k n n
e l e a i
r a h s g
e c o n h
s e m o t
n l e w x (补上一个x)

最初的想法是只用字符串,然后用一个i来指向,先算出长度l,确定需要几行,然后用i来控制,输出i取余行数为0的字母,再输出取余行数为1的字母依次类推……后来发现理解题目的意思错了,它是说,第一行从左到右,第二行从右到左,第三行从左到右……所以还是需要用二维数组。

然后调了半天,特别是二维数组把我绕晕了……shame花了不少时间

下面是代码

#include<iostream>
#include<string>

using namespace std;

int main()
{
	int i, j, count, col, row;
	string A;
	char a[50][50];
	cin >> col;
	while( col )
	{
		cin >> A;
		row = A.length()/col;	//figure the number of rows out
		count = 0;
		for( i = 0; i < row; i++ ){
			if( i%2 == 0 )
				for( j = 0; j < col; j++ )
				{
					a[i][j] = A[count];
					count++;
				}
			else
				for( j = col-1; j >= 0; j--)
				{
					a[i][j] = A[count];
					count++;
				}
		}
		for( j = 0; j < col; j++ )
			for( i = 0; i < row; i++ )
				cout<< a[i][j];
		cout << endl;
		cin >> col;
	}
	return 0;
}

看了别人的代码,好像还有另一种方法,差别是放到二维数组中的时候是不考虑单双行,输出的时候才考虑。其实差不多是吧。

好累,学霸之路好遥远QAQ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值