HDU-5459 Jesus Is Here(思维递推)

本文介绍了一种使用斐波那契数列解决特定字符串问题的方法,即计算字符串中所有字符‘c’间的坐标差之和。通过分析串与斐波那契数列的关系,给出了高效的计算公式及其实现代码。

题意:

求串s[n]中所有字符‘c'之间的坐标差的和。

思路:

可以发现一个串中c的个数和该串的长度都是一个斐波那契数,然后分析当前串s[n]对应的答案F[n],首先F[n-1]+F[n-2]是答案的一部分值,再看当前串和前面两个串的关系,得到剩余的部分值等于s[n-2]串中的c的个数*s[n-1]中所有c到开头的距离之和,再加上s[n-1]串中的c的个数*s[n-2]中所有c到末尾的距离之和,从而这样就覆盖了所有的组合情况。

代码:

#include <bits/stdc++.h>
#define LL long long
using namespace std;
const LL mod = 530600414;
const int maxn = 201315;
LL ans[maxn];
LL f[maxn], pre[maxn], las[maxn];
LL cnt[maxn];
int t, n;
void init()
{
	ans[3] = ans[4] = 0;
	f[3] = 3, f[4] = 5;
	pre[3] = 1, pre[4] = 3;
	las[3] = 2, las[4] = 2;
	//把c只归为到到末尾的部分,或者到开头的部分,避免重复统计 
	//pre[3] = 0, pre[4] = 2;
	//las[3] = 3, las[4] = 3;
	cnt[3] = cnt[4] = 1;
	for(int i = 5; i <= 201314; ++i)
	{
		f[i] = (f[i-1]+f[i-2])%mod;
		cnt[i] = (cnt[i-1]+cnt[i-2])%mod;
		pre[i] = (pre[i-1]+f[i-2]*cnt[i-1]%mod+pre[i-2])%mod;
		las[i] = (las[i-2]+f[i-1]*cnt[i-2]%mod+las[i-1])%mod;
		ans[i] = ((ans[i-1]+ans[i-2])%mod+pre[i-1]*cnt[i-2]%mod+las[i-2]*cnt[i-1]%mod)%mod;
	}
}
int main()
{
	init(); scanf("%d", &t);
	for(int _ = 1; _ <= t; ++_)
	{
		scanf("%d", &n);
		printf("Case #%d: %lld\n", _, ans[n]);
	}
	return 0;
}


继续加油~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值