Advanced Fruits HDU - 1503

題目傳送門

題意:給你兩個字符串把這兩個字符串合併起來,公共子串只輸出一次。

思路:這個題目記錄一下路徑就可以了,一開始沒有看到是Special judge想了很久的輸出方案,如果是Special judge就直接標記了以後輸出就可以了。

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>

#define MAXN 110
#define MAXE 5
#define INF 1000000000
#define MOD 10007
#define LL long long
#define ULL unsigned long long
#define pi 3.14159

using namespace std;

int dp[MAXN][MAXN];
int p[MAXN][MAXN];
string str1, str2;

void print(int x, int y) {
    if (x == 0 && y == 0) {
        return;
    }
    if (p[x][y] == 1) {
        print(x - 1, y - 1);
        cout << str1[x - 1];
    } else if (p[x][y] == 2) {
        print(x, y - 1);
        cout << str2[y - 1];
    } else if (p[x][y] == 3){
        print(x - 1, y);
        cout << str1[x - 1];
    } else {
        if (x > 0) {
            print(x - 1, y);
            cout << str1[x -1];
        } else if (y > 0) {
            print(x, y - 1);
            cout << str2[y -1];
        }
    }
}

int main() {
    std::ios::sync_with_stdio(false);
    while (cin >> str1 >> str2) {
        memset(dp, 0, sizeof(dp));
        for (int i = 1; i <= str1.length(); ++i) {
            for (int j = 1; j <= str2.length(); ++j) {
                if (str1[i - 1] == str2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    p[i][j] = 1;
                } else if (dp[i][j - 1] >= dp[i - 1][j]) {
                    dp[i][j] = dp[i][j - 1];
                    p[i][j] = 2;
                } else {
                    dp[i][j] = dp[i - 1][j];
                    p[i][j] = 3;
                }
            }
        }
        print((int) str1.length(), (int) str2.length());
        cout << endl;
    }
    return 0;
}
發佈了130 篇原創文章 · 獲贊 25 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章