4163: Encrypt
描述
Every evening, little Ivica sends secret messages to little Marica through e-mail. Knowing Ivica's e-letter travels unguarded through the network on its way to Marica's e-mailbox, they have decided to encrypt every message using the following algorithm:
· Suppose Ivica's message consists of N characters.
· Ivica must first find a matrix consisting of R rows and C columns such that R ≤ C and R·C = N. If there is more than one such matrix, Ivica chooses the one with the most rows.
· Ivica writes his message into the matrix in row-major order. In other words, he writes the first segment of the message into the first row, the second segment into the second row and so on.
· The message he sends to Marica is the matrix read in column-major order.
Marica has grown tired of spending her precious time deciphering Ivica's messages, so you must write a program to do it for her.
输入
The input contains the received message, a string of lowercase letters of the English alphabet (with no spaces).
The number of letters will be between 1 and 100.
输出
Output the original (decrypted) message.
样例输入
koaski
样例输出
kakosi
题目来源
题目链接:http://tzcoder.cn/acmhome/problemdetail.do?&method=showdetail&id=4163
题目大意:将一个字符串,转换成一个R*C的矩形字符串,要求R和C的值最接近,并且R*C=N,R<C,然后按照这个矩形输出
要求R和C最接近,那么R=C的时候是接近的,所以我们从R=sqrt(N)开始向下枚举到可以被整除为止,这样的R和C就是满足题目要求的,后面就按照题目意思模拟。
#include <math.h> #include <string.h> #include <stdio.h> int main() { char a[111]; char b[111][111]; while(scanf("%s",a)){ int n=strlen(a); int k=sqrt(n+1); //从最接近的开始向下枚举K,直到N能被K整除 while(n%k)k--; int i,j,l=0; //按照题目意思转换成二维数组 for(i=0;i<n/k;i++){ for(j=0;j<k;j++){ b[i][j]=a[l++]; } } //按照题目意思从前往后遍历输出 for(j=0;j<k;j++){ for(i=0;i<n/k;i++){ printf("%c",b[i][j]); } } puts(""); } }