Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Re:贴个代码(记忆递归,普通递归行不通):

Posted by lsz at 2011-05-05 20:16:03 on Problem 2696
In Reply To:贴个代码(记忆递归,普通递归行不通): Posted by:0810311106 at 2009-11-01 16:51:31
> 注意题中的mod的定义部分是r从0到q-1,当满足后面的条件时就取此时的r作为mod的结果~!
> 
> #include"iostream"
> using namespace std;
> int mod(int a,int b)
> {
> 	int r;
> 	for(r=0;r<=b-1;r++)
> 		if((a-r)%b==0)
> 			return r;
> }
> int main()
> {
> 	int n;
> 	cin>>n;
> 	 while(n--)
> 	 {
> 		 int a,b,c,d,e,f,g,h,i;
> 		 int s[1001],k;
> 		 cin>>a>>b>>c>>d>>e>>f>>g>>h>>i;
> 		 s[0]=a;
> 		 s[1]=b;
> 		 s[2]=c;
> 		 for(k=3;k<=i;k++)
> 			 if(k%2==0)
> 				 s[k]=mod(f*s[k-1]-d*s[k-2]+e*s[k-3],h);
> 			  else
> 				  s[k]=mod(d*s[k-1]+e*s[k-2]-f*s[k-3],g);
> 		 cout<<s[i]<<endl;
> 	 }
> 	 return 0;
> }

楼上的是递推,贴个记忆递归。

#include <iostream>
using namespace std;

int mod(int p, int q)
{
	int r = p % q;
	while (r < 0)
	{
		r += q;
	}
	return r;
}

const int N = 1024;
int dp[N];

int phi(int d, int e, int f, int g, int h, int i)
{
	if (dp[i] == -1)
	{
		if (i % 2 == 1)
		{
			dp[i] = mod(d*phi(d,e,f,g,h,i-1) + e*phi(d,e,f,g,h,i-2) - f*phi(d,e,f,g,h,i-3), g);
		} 
		else
		{
			dp[i] = mod(f*phi(d,e,f,g,h,i-1) - d*phi(d,e,f,g,h,i-2) + e*phi(d,e,f,g,h,i-3), h);
		}
	} 
	return dp[i];
}

int main()
{
	int n;
	cin>>n;
	while (n--)
	{
		int a, b, c, d, e, f, g, h, i;
		cin>>a>>b>>c>>d>>e>>f>>g>>h>>i;
		memset(dp, -1, sizeof(int) * N);
		dp[0] = a;
		dp[1] = b;
		dp[2] = c;
		int r = phi(d,e,f,g,h,i);
		cout<<r<<endl;
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator