Codeforces Round #418 (Div. 2) C. An impassioned circulation of affection (DP)

题目链接
题解:简单DP, dp[ch][ i ][ j ] 表示到第 i 位为止填了 j 个 ch 字母空位的最长连续长度,如果用 ans[ch][i] 表示 ch 字母至多填 i 次空位的最大连续长度,则 dp 数组可以省去一维。

#include 
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define P pair
#define debug(x) cout << (#x) << ": " << (x) << " "
#define fastio ios::sync_with_stdio(false), cin.tie(0)
#define mod 1000000007
const int M = 1000000 + 10;
const int N = 1500 + 10;

int n, q, m;
char s[N], c;
int dp[N][N], ans[26][N];

signed main()
{
    scanf("%d %s %d", &n, s + 1, &q);
    for(char ch = 'a'; ch <= 'z'; ++ ch) {
        memset(dp, 0, sizeof dp);
        for(int i = 1; i <= n; ++ i) {
            if(s[i] == ch) dp[i][0] = dp[i - 1][0] + 1;
            else dp[i][0] = 0;
        }
        for(int i = 1; i <= n; ++ i) {
            for(int j = 1; j <= i; ++ j) {
                if(s[i] == ch) dp[i][j] = dp[i - 1][j] + 1;
                else dp[i][j] = dp[i - 1][j - 1] + 1;
                ans[ch - 'a'][j] = max(ans[ch - 'a'][j], dp[i][j]);
            }
        }
        for(int i = 1, ma = 0; i <= n; ++ i) {
            ma = max(ma, ans[ch - 'a'][i]);
            ans[ch - 'a'][i] = ma;
        }
    }
    for(int i = 1; i <= q; ++ i) {
        scanf("%d %c", &m, &c);
        printf("%d\n", ans[c - 'a'][m]);
    }
    return 0;
}

/*

  Rejoicing in hope, patient in tribulation .

*/

你可能感兴趣的:(动态规划/思维)