sicily 1007

来源:互联网 发布:mac口红滋润系列 编辑:程序博客网 时间:2024/04/29 12:03

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.

Input

There will be multiple input sets. Input for each set will consist of two lines. The first line will contain an integer in the range 2 . ..20 indicating the number of columns used. The next line is a string of up to 200 lower case letters. The last input set is followed by a line containing a single 0, indicating end of input.

Output

Each input set should generate one line of output, giving the original plaintext message, with no spaces.

 

题目要求:将加过密的信息解密输出,加密规则为,将原来的句子的字母分为n组,依次放在一个矩阵的n列中,最后不足的用随意的字母补上,然后从首字母读起,按照蛇形读完,如:

原来的句子:theresnoplacelikehomeonasnowynight

约定矩阵有5

字母放在矩阵中:(最后一个字母是加上去的)

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

蛇形读取为toioynnkpheleaigshareconhtomesnlewx,即为密码

解密算法:

将一个字符串按照蛇形放入矩阵(二维数组),再一列一列地打印数组元素即可。

代码如下:

//sicily1007 2010-9-30
#include<iostream>
#include<string>
using namespace std;

int main()
{
 int n,m,i,j,key;
 char arr[200][200];
 string s;
 while(1){
  key=0;//用来实现蛇形读取
  i=0;
  j=0;
  cin>>n;
  if(n==0) break;
  cin>>s;
  m=s.size()/n;
  //cout<<m<<endl;
  string::iterator it=s.begin();
  for(i=0;i<m;i++){
   //改变同一行的读取方向
   if(key==0) key=1;
   else key=0;
   if(key==0){
    for(j=n-1;j>=0;j--){
    
    arr[i][j]=*it;
    it++;
    }
   }
   else{
    for(j=0;j<n;j++){
    
    arr[i][j]=*it;
    it++;
    }
   }
  }
  for(j=0;j<n;j++){
   for(i=0;i<m;i++) cout<<arr[i][j];
  }
  cout<<endl;
 }
 return 0;
}

原创粉丝点击