《算法竞赛入门经典(第2版)》 作者:刘汝佳
第三章习题3-1 输入O和X组成的串,统计得分
https://uva.onlinejudge.org//index.php?option=com_onlinejudge&Itemid=8&category=827
//采用二维字符串数组str来存储纵向字符串,利用与字符串序号与数组行的对应关系,
//实现了字符串的自动排序---------------------------------------E3-6.cpp---------------------------------------
#include <stdio.h>
#include <string.h>#define LOCAL
#define maxm 12
#define maxn 101
int main()
{
#ifdef LOCAL
freopen("E3-6.in", "r", stdin);
#endif
int row, col, kase = 1;
while(scanf("%d%d", &row, &col) == 2 && row) {
char puzzle[row][col];
int val[row][col];
memset(val, 0, sizeof(val));
for(int i = 0; i < row; i++)
scanf("%s", puzzle[i]); //构造puzzle串
if(kase > 1) printf("\n");
printf("puzzle #%d:\nAcross", kase++);
int count = 1;
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++) {
if(puzzle[i][j] == '*') continue;
if( i-1<0 || j-1<0 ) val[i][j] = count++;
else if( puzzle[i-1][j]=='*' || puzzle[i][j-1]=='*' ) val[i][j] = count++;
}//计算每个非*字母的序列号
for(int i = 0; i < row; i++) {
int neword = 1;//新字符串标志,遍历puzzle,逐个输出
for(int j = 0; j < col; j++) {
if(j == 0) neword++;//每行都开始一个新字符串
if(puzzle[i][j] == '*') neword++;//*意味着一个新字符串
else if(neword > 0) {printf("\n%3d.%c", val[i][j], puzzle[i][j]); neword = 0;}
else printf("%c", puzzle[i][j]);
}
}//输出横向Across的字符串
printf("\nDown\n");
char str[count][maxm];//纵向字符串遍历顺序和输出顺序不一致,需要先暂存到字符串数组中
memset(str, 0, sizeof(str));
for(int j = 0; j < col; j++) {
int neword = 1, save = 0, tempi = 0;
for(int i = 0; i < row; i++) {
if(i == 0) neword++;
if(puzzle[i][j] == '*') neword++;
else if(neword > 0) {
save = 0;//str中某行的第save个字符
tempi = val[i][j]; //字符串首字母的序号val与str的行号相同
str[tempi][save++] = puzzle[i][j];
neword = 0;
}
else str[tempi][save++] = puzzle[i][j]; //存入到所在字符串的首字母序号所对应的str行中
}
}//产生纵向Down字符串并暂存至str中
for(int i = 0; i < count; i++)
if(str[i][0] != 0) printf("%3d.%s\n", i, str[i]);
}
return 0;
}
--------------------------------------------E3-6.in的分界线--------------------------------------
9 9
ANTIC*ACEDOUCE*MUG
ARTILLERY
**ELL*NIP
HOLY*RIOT
ARA*VAT**
SIGNIFIED
TOE*STERE
ENS*ASSAY
9 9
*LAUREL**
PASSERINE
EST*CABER
WHOA*SETA
**UTTER**
LINT*RARE
INDIE*TON
INERTNESS
**DECODE*
9 9
OREO*EBON
LAMP*RODE
EGOTISTIC
OATS*TANK
**I***N**
UPON*LIVE
SYNODICAL
ERAS*MASS
DELE*ALEE
1 1
*
1 1
Z
6 5
*****
*HAIR
RI*L*
E*ILD
****Z
*****
0
//采用二维字符串数组str来存储纵向字符串,利用与字符串序号与数组行的对应关系,
//实现了字符串的自动排序