1 条题解

  • 0
    @ 2025-6-10 20:18:37

    题意分析

    题目要求实现一种文本压缩方案的解压过程。该压缩方案对不含数字的文件进行处理:将非字母字符直接复制,首次出现的单词也直接复制并加入列表头部,重复出现的单词则用其在列表中的位置(从1开始编号)替代,并将该单词移至列表头部。输入为压缩后的文件(包含数字和非字母字符),输出为原始未压缩文件。需注意单词区分大小写,且原始文件不含数字。

    解题思路

    代码使用链表模拟列表操作:1)维护链表头指针head和单词节点数组word;2)按顺序读取输入字符,若为数字则解析位置编号,找到对应单词并输出,同时将其移至链表头部;若为字母则读取完整单词并输出,同时将其加入链表头部;若为非字母字符则直接输出。通过链表的动态调整实现"移至头部"操作,确保每次访问后单词顺序符合压缩规则。

    
    #include <iostream>
    #include <stdio.h>
    #include <ctype.h>
    
    using namespace std;
    
    const int N = 10000;
    struct Node {
        string word;
        int next;
    } word[N];
    int wcnt = 0, head;
    
    int main()
    {
        char c;
        c = getchar();
        for (;;) {
            if (c == '0') break;
            else if (isdigit(c)) {
                int num = 0;
                while (isdigit(c)) {
                    num *= 10;
                    num += c - '0';
                    c = getchar();
                }
    
                int cur = head, prev;
                for (int i = 1; i < num; i++) {
                    prev = cur;
                    cur = word[cur].next;
                }
    
                printf("%s", word[cur].word.c_str());
    
                if (cur != head) {
                    word[prev].next = word[cur].next;
                    word[cur].next = head;
                    head = cur;
                }
            }
            else if (isalpha(c)) {
                string t;
                while (isalpha(c)) {
                    t += c;
                    c = getchar();
                }
                printf("%s", t.c_str());
                word[wcnt].word = t;
                word[wcnt].next = head;
                head = wcnt++;
            }
            else {
                putchar(c);
                c = getchar();
            }
        }
    
        return 0;
    }
    
    
    • 1

    信息

    ID
    886
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    1
    已通过
    1
    上传者