1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| #include <set> #include <map> #include <queue> #include <stack> #include <deque> #include <cmath> #include <bitset> #include <cstdio> #include <vector> #include <string> #include <complex> #include <utility> #include <cstring> #include <iostream> #include <assert.h> #include <algorithm>
using namespace std; #define FO(x) freopen(#x".in","r",stdin),freopen(#x".out","w",stdout) #define ll long long #define ull unsigned ll #define db double #define lb long db #define pb push_back #define com complex<db> #define mp(x,y) make_pair((x),(y)) #define fi first #define se second #define all(x) (x).begin(),(x).end() #define cle(x) memset(x,0,sizeof(x)) #define lowbit(x) ((x)&(-(x))) #define bit(x,i) (((x)>>(i))&1) #define fo(i,j,k) for(int i=(j),end_i=(k);i<=end_i;i++) #define fd(i,j,k) for(int i=(j),end_i=(k);i>=end_i;i--) inline int read() { int x=0; char ch=getchar(); bool f=0; for(;ch<'0'||ch>'9';ch=getchar()) if(ch=='-') f=1; for(;ch>='0'&&ch<='9';ch=getchar()) x=(x<<3)+(x<<1)+(ch^48); return f?-x:x; } const int N=5e5+5; const int S=26; const ll inf=1e18;
namespace AC{ int ne[N][S],val[N],len[N],fail[N],cnt,anc[N]; inline void ins(char *s,int v) { int u=0,c,n=strlen(s); for(int i=0;i<n;i++) { c=s[i]-'a'; if(!ne[u][c]) ne[u][c]=++cnt; u=ne[u][c]; } if(!val[u]) val[u]=v; else val[u]=min(val[u],v); len[u]=n; } queue<int> q; void getfail() { q.push(0); for(int u,v;!q.empty();) { u=q.front(); q.pop(); anc[u]=val[fail[u]]?fail[u]:anc[fail[u]]; for(int i=0;i<S;i++) if(v=ne[u][i]) { if(!u) fail[v]=0; else fail[v]=ne[fail[u]][i]; q.push(v); } else ne[u][i]=ne[fail[u]][i]; } } ll f[N]; inline ll work(char *s) { int n=strlen(s+1); f[0]=0; for(int i=1,u=0;i<=n;i++) { f[i]=inf; u=ne[u][s[i]-'a']; for(int j=u;j;j=anc[j]) f[i]=min(f[i],f[i-len[j]]+val[j]); } if(f[n]==inf) return -1; return f[n]; } } int n; char s[N]; int main() { n=read(); fo(i,1,n) {scanf("%s",s); AC::ins(s,read());} AC::getfail(); scanf("%s",s+1); printf("%lld\n",AC::work(s)); return 0; }
|