解法:正难则反,我们设dp[u]为从u点出发到不了最深的叶子节点概率,设sz[u]为u节点儿子数量,不难想到
d
p
[
u
]
=
(
1
s
z
[
u
]
∑
s
o
n
d
p
[
s
o
n
]
)
s
z
[
u
]
dp[u]=(\frac{1}{sz[u]}\sum_{son}dp[son])^{sz[u]}
dp[u]=(sz[u]1∑sondp[son])sz[u]
#include<bits/stdc++.h>#define ll long long
using namespace std;constint maxn =1e6+10, mod =1e9+7;
vector<int> G[maxn];int sz[maxn], dep[maxn], mx, d[maxn];voidadd(int&x,int y){
x += y;if(x >= mod)
x -= mod;if(x <0)
x += mod;}
ll ksm(ll x,int y){
ll res =1;while(y){if(y &1)
res = res * x % mod;
x = x * x % mod;
y /=2;}return res;}voiddfs(int u,int fa){
dep[u]= dep[fa]+1;
mx =max(mx, dep[u]);for(auto v : G[u])if(v != fa){
sz[u]++;dfs(v, u);}}intdfs2(int u,int fa){if(!sz[u])return(mx != dep[u]);int inv =ksm(sz[u], mod -2), ans =0;for(auto v : G[u])if(v != fa)
ans =(ans +1ll* inv *dfs2(v, u)% mod)% mod;returnksm(ans, sz[u]);}intmain(){int n, u, v;scanf("%d",&n);for(int i =1; i < n; i++){scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);}dfs(1,0);int ans =1-dfs2(1,0);add(ans,0);printf("%d\n", ans);}
解法:设
d
p
[
i
]
[
c
]
=
p
dp[i][c] = p
dp[i][c]=p 为
s
s
s串前
i
−
1
i - 1
i−1个字符,下一次即将匹配
t
t
t串最大的下标
p
p
p满足
t
[
p
]
=
c
t[p] = c
t[p]=c,假如
s
[
i
]
=
c
s[i] = c
s[i]=c,那么显然对于所有
j
<
c
j < c
j<c,
a
n
s
=
m
a
x
(
a
n
s
,
d
p
[
i
]
[
j
]
−
1
+
n
−
i
+
1
)
ans = max(ans, dp[i][j] - 1 + n - i + 1)
ans=max(ans,dp[i][j]−1+n−i+1),当然我也可以继续相等的匹配,令
x
=
d
p
[
i
]
[
c
]
+
1
x = dp[i][c] + 1
x=dp[i][c]+1,
d
p
[
i
+
1
]
[
t
[
x
]
]
=
m
a
x
(
d
p
[
i
+
1
]
[
t
[
x
]
]
,
d
p
[
i
]
[
x
]
+
1
)
dp[i + 1][t[x]] =max(dp[i + 1][t[x]], dp[i][x] + 1)
dp[i+1][t[x]]=max(dp[i+1][t[x]],dp[i][x]+1)
#include<bits/stdc++.h>
using namespace std;constint maxn =1e6+10, inf =1e9;char s[maxn], t[maxn];int dp[maxn][26];intmain(){int n, len;scanf("%d%d",&n,&len);scanf("%s%s", s +1, t +1);int cat =-1;for(int i =0; i <26; i++)
dp[0][i]=-inf;
dp[0][t[1]-'a']=1;for(int i =1; i <= n; i++){int c = s[i]-'a';for(int j =0; j <26; j++)
dp[i][j]= dp[i -1][j];for(int j = c -1;~j; j--)
cat =max(cat, dp[i][j]-1+ n - i +1);if(dp[i][c]== len && i < n)
cat =max(cat, dp[i][c]-1+ n - i +1);if(dp[i][c]!=-inf && dp[i][c]< len){int x = dp[i][c]+1;int cc = t[x]-'a';
dp[i][cc]=max(dp[i][cc], dp[i][c]+1);}}printf("%d\n", cat);}