程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> HDU 5642 King's Order(數位DP)

HDU 5642 King's Order(數位DP)

編輯:關於C++

題意:要求你生成一個合法的字符串, 由小寫字母a~z組成, 相同字母相鄰出現不能超過3個, 求有多少種組合。

思路:數位DP來做, 用d[i][j][k]表示處理完前i個字母, 第i-1個字母為j,已經連續出現了k次的方法數。 然後每次轉移就很簡單了, 繼續選擇字母j(if(k < 3)), 或者換其他的。

細節參見代碼:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
typedef long double ld;
const ld eps = 1e-9, PI = 3.1415926535897932384626433832795;
const ll mod = 1000000000 + 7;
const int INF = 0x3f3f3f3f;
// & 0x7FFFFFFF
const int seed = 131;
const ll INF64 = ll(1e18);
const int maxn = 2000 + 10;
int T,n,m,d[maxn][30][5],vis[maxn][30][5],kase=0;
int dp(int i, int j, int k) {
    int& ans = d[i][j][k];
    if(i == n+1) return 1;
    if(vis[i][j][k] == kase) return ans;
    vis[i][j][k] = kase;
    ans = 0;
    if(k < 3 && i != 1) {
        ans += dp(i+1, j, k+1);
        if(ans >= mod) ans -= mod;
    }
    for(int l=0;l<26;l++) {
        if(l == j) continue;
        ans += dp(i+1, l, 1);
        if(ans >= mod) ans -= mod;
    }
    return ans;
}
int main() {
    scanf("%d",&T);
    while(T--) {
        scanf("%d",&n);
        ++kase;
        int ans = dp(1, 27, 0);
        printf("%d\n",ans);
    }
    return 0;
}


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved