您的位置:首页 > 编程语言 > C语言/C++

1007[To and Fro]

2013-10-10 15:27 489 查看


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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sicily c++