传送门:2020ICPC新疆省赛 - A
思路分析
不难写出一个$dp$式子$:dp[i][j] = max(dp[i-1][pre]+val[j])$,其中$pre$表示上一个可能的状态通过一个字符转移到$j$
这个式子很像另一个矩阵的经典运用,一个有向图,告诉起点和终点,求恰好$k$步走到终点的方案,所以可以用矩阵快速幂来优化
AC代码
// Problem: Chino With String
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/contest/16792/A
// Memory Limit: 524288 MB
// Time Limit: 2000 ms
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (int)(x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
#define int long long
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
const int INF = 1e18;
const double PI = acos(-1);
const int N = 1e6+10;
struct AC_auto {
struct T {
int son[26],fail,word,last;
void clear() {
mem(son,0);
word = fail = last = 0;
}
} tree[N];
int cnt = 1;
int val[N] ;
int newnode() {
++cnt;
tree[cnt].clear();
return cnt;
}
void init() {
cnt = 1;
mem(val,0);
tree[1].clear();
tree[1].word = 1;
}
void ins(string s,int w) {
int p = 1;
for(auto i:s) {
int c = i-'a';
if(!tree[p].son[c]) tree[p].son[c] = newnode();
p = tree[p].son[c];
}
tree[p].word = 1;
val[p] += w;
}
void getfail() {
for(int i=0; i<26; i++) tree[0].son[i] = 1;
queue<int>q;
q.push(1);
while(!q.empty()) {
int u = q.front();
q.pop();
int ufail = tree[u].fail;
tree[u].last = tree[ufail].word>0?ufail:tree[ufail].last;
val[u]+=val[tree[u].last];
for(int i=0; i<26; i++) {
int v = tree[u].son[i];
if(v) {
tree[v].fail = tree[ufail].son[i];
q.push(v);
} else tree[u].son[i] = tree[ufail].son[i];
}
}
}
} AC;
struct Mat{
int n;
vector<vector<int>>a;
Mat(){}
Mat(int nn){
n = nn;
a.resize(n+2);
for(int i=1;i<=n;i++) a[i].resize(n+2);
for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) a[i][j] = -INF;
}
Mat operator * (const Mat &B) const {
Mat res(n);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
res.a[i][j] = -INF;
for(int k=1;k<=n;k++){
res.a[i][j] = max(res.a[i][j],a[i][k]+B.a[k][j]);
}
}
}
return res;
}
Mat pow(int x){
Mat res(n) , bas(n);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j) res.a[i][j] = 0;
else res.a[i][j] = -INF;
}
}
bas.a = a;
while(x){
if(x&1) res = res*bas;
x>>=1;
bas = bas*bas;
}
a = res.a;
return res;
}
};
signed main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
int n,m;
cin>>n>>m;
AC.init();
for(int i=1;i<=m;i++){
string x;
int w;
cin>>x>>w;
AC.ins(x,w);
}
AC.getfail();
int len = AC.cnt+1;
Mat dp(len+1);
for(int i=1;i<=len;i++){
for(int j=0;j<26;j++){
dp.a[i][AC.tree[i].son[j]] = AC.val[AC.tree[i].son[j]];
}
}
dp.pow(n);
int ans = -INF;
for(int i=1;i<=len;i++) ans = max(ans,dp.a[1][i]);
cout<<ans<<endl;
return 0;
}