• coj 1100 Magic Spell


    这道题的HINT彻底把我弄糊涂了,结果WA5次才发现是求最大子序列而不是连续子串:

    HINT

    子序列的定义:字符串S中从S[ i ]...S[ j ]的长度为K的字符(i<=j),k<=j-i+1。

    # include <stdio.h>
    # include <memory.h>
    
    # define MAX(x, y) ((x)>(y) ? (x):(y))
    
    # define MAXN 1020
    
    int len1, len2;
    char s1[MAXN], s2[MAXN];
    short int f[MAXN][MAXN];
    
    int main()
    {
        int i, j, max;
    
        while (~scanf("%d%s%d%s", &len1, s1+1, &len2, s2+1))
        {
            max = 0;
            memset(f, 0, sizeof(f));
    
            for ( i = 1; i <= len1; ++i)
                for ( j = 1; j <= len2; ++j)
                {
                    if (s1[i] == s2[j]) f[i][j] = f[i-1][j-1]+1;
                    else f[i][j] = MAX(f[i-1][j], f[i][j-1]);
                }
    
            printf("%d\n", f[len1][len2]);
        }
    
        return 0;
    }

    不过也顺便复习了一下最大子串的方法,很相似, 都可以使用滚动数组。

    # include <stdio.h>
    # include <memory.h>
    # include <ctype.h>
    
    # define MAXN 1020
    
    int len1, len2;
    char s1[MAXN], s2[MAXN];
    short int f[MAXN][MAXN];
    
    int main()
    {
        int i, j, max;=
    
        while (~scanf("%d%s%d%s", &len1, s1+1, &len2, s2+1))
        {
            max = 0;
            memset(f, 0, sizeof(f));
    
            for ( i = 1; i <= len1; ++i)
                for ( j = 1; j <= len2; ++j)
                {
                    if (tolower(s1[i]) == tolower(s2[j])) f[i][j] = f[i-1][j-1]+1;
                    if (max < f[i][j]) max = f[i][j];
                }
    
            printf("%d\n", max);
        }
    
        return 0;
    }

     

  • 相关阅读:
    【POJ】1287 Networking
    【POJ】1251 Jungle Roads
    【POJ】1182 食物链
    【POJ】2492 A Bug's Life
    【HDUOJ】1213 How many tables
    【POJ】1611 The Suspects
    【POJ】2236 Wireless Network
    【POJ】2240 Arbitrage
    【POJ】3660 Cow Contest
    【POJ】1502 MPI Maelstrom
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2446597.html
Copyright © 2020-2023  润新知