acm--the benefits of using the array storage calculation process for program efficiency

Source: Internet
Author: User

Topic Background:


Solution One:

#include <iostream>
using namespace std;
int main ()
{
	long long getstep (int, int);
	int n,a,b;
	cin>>n;
	while (n--)
	{
		cin>>a>>b;
		Cout<<getstep (A, B) <<endl;
	}
	return 0;
}

Long long getstep (int a, int b)
{
	b = B-(A-1);//actually equivalent to only 1 parameters b,a to B converted from 1 to T (t here is the updated B,a is 1), the steps are the same 
	if (b = = 2)
	{
		return 1;
	} 
	if (b = = 3)
	{
		return 2; 
	}
	Long Long f1 = 1;
	Long Long F2 = 2;
	Long long step;
	for (int i=3; i<b; i++)
	{
		step = f1 + F2;
		f1 = F2;
		F2 = step;
	}
	return step; 
}

Solution Two:

#include <iostream>
using namespace std;

int main ()
{
	int n,a,b;
	Long long resultarray[52];
	Resultarray[0] = 0;
	RESULTARRAY[1] = 1;
	RESULTARRAY[2] = 2;
	for (int i=3; i<52; i++)
	{
		Resultarray[i] = resultarray[i-1] + resultarray[i-2];
	} 
	cin>>n;
	while (n--)
	{
		cin>>a>>b;
		cout<<resultarray[b-a]<<endl;
	}
	return 0;
}
Results Analysis:

With this simple example, we can see the benefits of using an array to store the computational process:

1: Code Simplicity

2: High efficiency, as long as the calculation once, then all the results are put in the inside, only need to go to the corresponding location to fetch the data.

3: Simple logic, clear thinking

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.