跳到正文

题解

题解:CF1811G2 Vlad and the Nice Paths (hard version)

hjyowl约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年4月9日
收录
2025年12月12日
更新
2026年10月9日
篇幅
约 4 分钟
获赞
3
题目
CF1811G2

版本

  1. v1当前

思路

特殊条件子序列计数,考虑动态规划。

定义 fif_i 为从 11 到 ii 最长的好路径长度,cnticnt_i 为 11 到 ii 的最长好路径数量,两者都需要满足以 ii 结尾。

考虑枚举 ii,倒着往前枚举 jj,令 tt 为 jj 到 ii 中和 aia_i 一样的数的个数。

对于 k≤tk \le t 时,更新 fif_i,如果 fj+k≤fif_j+k \le f_i,那么 fif_i 等于 fj+kf_j+k 然后数量等于 cntj×Ct−1k−1cnt_j \times C_{t-1}^{k-1}。如果 fif_i 等于 fj+kf_j+k 那就把 cnticnt_i 加上 cntj×Ct−1k−1cnt_j \times C_{t-1}^{k-1}。

至于为什么是 cntj×Ct−1k−1cnt_j \times C_{t-1}^{k-1},前面的 cntjcnt_j 是 11 到 jj 的方案,Ct−1k−1C_{t-1}^{k-1} 是 j+1j+1 到 ii 那 t−1t-1 个里面选择 k−1k-1 个(因为必须选择 aia_i)。

代码

C++
#include <bits/stdc++.h>
using namespace std;
const long long N = 5010,mod = 1e9 + 7;
long long qmi(long long a,long long k){
	long long res = 1;
	while (k){
		if (k & 1){
			res = (res * a) % mod;
		}
		a = (a * a) % mod;
		k >>= 1;
	}
	return res;
} 
long long fact[N],infact[N];
long long n,k;
long long a[N];
long long f[N],cnt[N];
long long C(long long a,long long b){
	return ((fact[a] * infact[b]) % mod) * infact[a - b] % mod;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	long long T;
	cin >> T;
	fact[0] = 1;
	for (long long i = 1; i < N; i ++ ){
		fact[i] = fact[i - 1] * i % mod;
	}
	for (long long i = N - 1; i >= 0; i -- ){
		infact[i] = qmi(fact[i],mod - 2);
	}
	while (T -- ){
		cin >> n >> k;
		memset(f,0,sizeof f);
		memset(cnt,0,sizeof cnt);
		for (long long i = 1; i <= n; i ++ ){
			cin >> a[i];
		}
		cnt[0] = 1; 
		for (long long i = k; i <= n; i ++ ){
			long long s = 0;
			for (long long j = i; j >= 0; j -- ){
				if (s >= k){
					long long c = f[j] + k,t = (C(s - 1,k - 1)) % mod;
					if (c > f[i]){
						f[i] = c;
						cnt[i] = (cnt[j] * t) % mod;
					}
					else if (c == f[i]){
						cnt[i] = (cnt[i] + (cnt[j] * t) % mod) % mod;
					}
				}
				if (a[i] == a[j]){
					s ++ ;
				}
			}
		}
		long long mx = -1e9,res = 0;
		for (long long i = 0; i <= n; i ++ ){
			if (f[i] > mx){
				mx = max(mx,f[i]);
				res = 0;
				res = (res + cnt[i]) % mod;
			}
			else if (f[i] == mx){
				res = (res + cnt[i]) % mod;
			}
		}
		cout << res << endl;
	}
	return 0;
} 
原文