HDU1020 ZOJ2478 Encoding
问题链接:HDU1020 ZOJ2478 Encoding。入门练习题,用C语言编写程序。
这是一个输入流处理的程序,最佳方案是一边读入一边处理。
这里给出两个C语言程序,有个比较。一个是用gets()函数把每行的字符串读入到字符数组中再行处理;另外一个是用getchar()函数逐个读入字符处理。
AC的C语言程序(正解)如下:
/* HDU1020 ZOJ2478 Encoding */
#include <stdio.h>
#define MAXN 10000
int main(void)
{
int n, count;
char in, c;
scanf("%d", &n);
getchar();
while(n--) {
count = 0;
c = '\0';
for(;;) {
in = getchar();
if(in == '\n')
break;
if(in != c) {
if(count != 0) {
if(count == 1)
putchar(c);
else
printf("%d%c", count, c);
}
c = in;
count = 1;
} else
count++;
}
if(count > 0) {
if(count == 1)
putchar(c);
else
printf("%d%c", count, c);
}
printf("\n");
}
return 0;
}另外一个版本,AC的C语言程序如下:
/* HDU1020 Encoding */
#include <stdio.h>
#include <stdlib.h>
#define MAXN 10000
int main(void)
{
int n, count;
char s[MAXN+1], c, *p;
gets(s);
n = atoi(s);
while(n--) {
gets(s);
count = 0;
c = '\0';
p = s;
while(*p) {
if(*p != c) {
if(count != 0) {
if(count == 1)
printf("%c", c);
else
printf("%d%c", count, c);
}
c = *p;
count = 1;
} else
count++;
p++;
}
if(count > 0) {
if(count == 1)
printf("%c", c);
else
printf("%d%c", count, c);
}
printf("\n");
}
return 0;
}
浙公网安备 33010602011771号