David_Jett

我要变得很强!!——2017-8-30

【打CF,学算法——三星级】CF Gym 100548K Last Denfence

【CF简介】

提交链接:Last Denfence


题面:

 Last Defence
Description
    Given two integers A and B. Sequence S is defined as follow:
    • S0 = A
    • S1 = B
    • Si = |Si−1 − Si−2| for i ≥ 2
    Count the number of distinct numbers in S.
Input
    The first line of the input gives the number of test cases, T. T test cases follow. T is about
    100000.
    Each test case consists of one line - two space-separated integers A, B. (0 ≤ A, B ≤ 1018).
Output
    For each test case, output one line containing “Case #x: y”, where x is the test case
    number (starting from 1) and y is the number of distinct numbers in S.
Samples
Sample Input 

   2
  7 4
  3 5

Sample Output
Case #1: 6
Case #2: 5


解题:

    过程便是辗转相减法,然而模拟这个过程会超时,改进为辗转相除法。直接拿大的数除小的数,即需要减的次数,加到结果中,最后结果便是答案。


代码:

#include <iostream>
using namespace std;
int main()
{
	long long int a,b,n,ans,tmp;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
	cout<<"Case #"<<i<<": ";
	  ans=0;
      cin>>a>>b;    
	  if(a==0&&b==0)
		 {
			 cout<<"1\n";
			 continue;
		 }
	   if(a==0||b==0)
		  {
			  cout<<"2\n";
			  continue;
		  }
	  while(b)
	  {
		  ans+=a/b;
		  tmp=b;
		  b=a%b;
		  a=tmp;
	  }
      cout<<ans+1<<endl;
	}
	return 0;
}

阅读更多
版权声明:欢迎交流! https://blog.csdn.net/David_Jett/article/details/46796489
所属专栏: 【打CF,学算法】
上一篇SPOJ COWPIC
下一篇HDU 5228 ZCC loves straight flush( BestCoder Round #41)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭