記憶化搜索+迴文串--UVA 10617 Again Palindrome

題目大意:

給你一個串,你可以刪掉任意個字符使其成爲迴文串,問有幾種方法。

解題思路:

一開始以爲可以用Manacher處理出輔助數組P,在通過組合數得到答案,發現結果不對。比賽結束後得知是記憶化搜索。。。

設數組DP[i][j]表示i到j的迴文串的種類個數,我們可以得到這樣的遞推關係:

DP[i][j] = DP[i+1][j] + DP[i][j-1] + 1;

但是這其中多了一部分就是DP[i+1][j-1]的重疊,因此我們需要減掉,但是如果s[i] == s[j]的話,我們可以知道DP[i+1][j-1]的任意一個迴文串都可以和s[i], s[j]組成新的迴文串,因此需要加上這一部分,所以這種情況下是不需要減掉的。

AC代碼:

#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <bitset>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include <cstring>
#include <iostream>
#include <algorithm>
#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;
//#define   maxd          1010
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
#define   mc(x, y)     memcpy(x, y, sizeof(x))
#define   ms(x,y)      memset(x,y,sizeof(x))
#define   rep(i,n)      for(int i=0;i<(n);i++)
#define   repf(i,a,b)   for(int i=(a);i<=(b);i++)
#define   PI           pair<int,int>
//#define   mapp            make_pair
#define   FI            first
#define   SE            second
#define   IT            iterator
#define   PB            push_back
#define   Times         10
typedef   long long     ll;
typedef   unsigned long long ull;
typedef   long double   ld;
typedef   pair<int,int > pce;
//#define N 100
const double eps = 1e-10;
const double  pi = acos(-1.0);
const  ll    mod = 1e9+7;
const  int   inf = 0x3f3f3f3f;
//const  ll    INF = (ll)1e18+300;
const int   maxd = 1010 + 10;
const int   maxx = 10100;
using namespace std;
typedef long long ll;

char ac[maxd];
ll dp[1010][1010];

ll DFS(int l, int r) {
    ll &ans = dp[l][r];
    if(ans > 0) {
        return ans;
    }
    if(r < l) {
        return ans = 0;
    }
    if(l == r) {
        return ans = 1;
    }
    if(ac[l] == ac[r]) {
        ans += DFS(l + 1, r);
        ans += DFS(l, r - 1);
        ans +=  1;
    }
    else {
        ans += DFS(l + 1, r);
        ans += DFS(l, r - 1);
        ans -= DFS(l + 1, r - 1);
    }
    return ans;
}
int main() {
    int t;
    cin >> t;
    while(t --) {
        scanf("%s", &ac);
        int len = strlen(ac);
        ms(dp, 0);
        ll ans = DFS(0, len - 1);
        cout << ans << endl;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章