UPC 5130 Concerts

UPC 5130 Concerts

Tag: dynamic programming


Description

John enjoys listening to several bands, which we shall denote using A through Z. He wants to attend several concerts, so he sets out to learn their schedule for the upcoming season.
He finds that in each of the following n days (1 ≤ n ≤ \(10^5\)), there is exactly one concert. He decides to show up at exactly k concerts (1 ≤ k ≤ 300), in a given order, and he may decide to attend more than one concert of the same band.
However, some bands give more expensive concerts than others, so, after attending a concert given by band b, where b spans the letters A to Z, John decides to stay at home for at least hb days before attending any other concert.
Help John figure out how many ways are there in which he can schedule his attendance, in the desired order. Since this number can be very large, the result will be given modulo \(10^9 + 7.\)

Input

The first line contains k and n. The second line contains the 26 hb values, separated by spaces.
The third line contains the sequence of k bands whose concerts John wants to attend e.g.,AFJAZ, meaning A, then F etc. The fourth line contains the schedule for the following n days,specified in an identical manner.

Output

The number of ways in which he can schedule his attendance (mod 109 + 7).

Sample Input

2 10
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
AB
ABBBBABBBBB

Sample Output

10

analyze

  • Because you have to wait a few days after participating in music each time before you can participate in others, it is more convenient to do DP backwards
  • Use \(dp[i][j]\) to represent the number of programs that participated in the \(jk\) th band in the \( in \)th concert.
  • The transfer equation can be obtained as, \(dp[i][j]=dp[i+1][j]+dp[i+1+hb(i)][j+1]\) , where \(hb( i)\) is the hb value of the band corresponding to the ith concert.

code

expand

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
typedef long long ll;
const ll MOD=1e9+7;
const int maxn=100005;
int dp[maxn][305];
int w[30];
char s1[maxn],s2[305];
int main(int argc, char const *argv[])
{
    int k,n;
    scanf("%d%d", &k,&n);
    for (int i = 0; i < 26; ++i)
    {
        scanf("%d", w+i);
    }
    scanf("%s", s2+1);
    scanf("%s", s1+1);
    ll ans=0;
    for (int i = n; i ; --i)
    {
        for (int j = k; j ; --j)
        {
            int &u=dp[i][j];
            u=dp[i+1][j];
            if(j==k&&s1[i]==s2[j]) u=(u+1)%MOD;
            else if(i+w[s1[i]-'A']+1<=n&&s1[i]==s2[j])
                u=((ll)dp[i+w[s1[i]-'A']+1][j+1]+(ll)u)%MOD;
        }
    }
    printf("%d\n", dp[1][1]);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324927690&siteId=291194637