codeforces 474D Flowers 动态规划

题目链接 http://codeforces.com/contest/474/problem/D

把红花和白花摆成一排,并且要求若出现白花,它们连续的数量必须是k的倍数。

给我们 n,接下来的n次询问。和k   (n,k<100000)

每行 一个 a[i],b[i]。

设f(k)为长度为k的满足条件的一排花 的 可能的数量

最后求f(a[i])+f(a[i+1])+...+f(b[i])

这道的代码比较难的是思路。

扫描二维码关注公众号,回复: 2693209 查看本文章

设dpw[i] 为 长度为i的可能数,且结尾是白花。

设dpr[i] 为 长度为i的可能书,且结尾是红花。

那么产生dpr[i],来源的路径为dpr[i-1]和dpw[i-1]

而dpw[i]要求连续的都是白色花,它的来源应该是 dpw[i-k]和dpr[i-k]。

代码如下

#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long LL;
typedef long long ll; 
const int maxn = 1e5+6;
const int modn = 1e9+7;
const int INF = 0x3f3f3f3f;
ll dpr[maxn];
ll dpw[maxn];
ll all[maxn];
void show(int a[],int n){
	for(int i=0;i<n;i++){
		printf("%d ",a[i]);
	}printf("\n");
}
int main(){
//	freopen("C:\\Users\\lenovo\\Desktop\\data.in","r",stdin);
	int n,k,aa,bb; 
	while(scanf("%d%d",&n,&k)!=EOF){
		memset(dpw,0,sizeof(dpw));
		memset(dpr,0,sizeof(dpr));
		dpw[0] = 0LL;
		dpr[0] = 1LL;
		all[0] = 1LL;
		for(int i=1;i<maxn-3;i++){
			dpr[i] = dpr[i-1]+dpw[i-1];
			if(i-k>=0)dpw[i] = dpr[i-k]+dpw[i-k];
			all[i] = dpr[i]+dpw[i]+all[i-1];
			dpr[i]%=modn;
			dpw[i]%=modn;
			all[i]%=modn;
		}

		for(int i=0;i<n;i++){
			scanf("%d%d",&aa,&bb);
			ll ans =  (all[bb]-all[aa-1]+modn)%modn;
			printf("%I64d\n",ans);
			
		}
	} 
}

猜你喜欢

转载自blog.csdn.net/qq_25955145/article/details/81264380