zoukankan      html  css  js  c++  java
  • 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 = '';
            for(;;) {
                in = getchar();
    
                if(in == '
    ')
                    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("
    ");
        }
    
        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 = '';
            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("
    ");
        }
    
        return 0;
    }

     

  • 相关阅读:
    pat1038. Recover the Smallest Number (30)
    pat1037. Magic Coupon (25)
    pat1036. Boys vs Girls (25)
    pat1031. Hello World for U (20)
    pat1030. Travel Plan (30)
    pat1028. List Sorting (25)
    pat1027. Colors in Mars (20)
    pat1017. Queueing at Bank (25)
    pat1025. PAT Ranking (25)
    Reverse Linked List II
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564570.html
Copyright © 2011-2022 走看看