文章标题 UVALive 7045:Last Defence(辗转相除思想)
2016-09-11 20:53
465 查看
Last Defence
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.
Sample Input
2
7 4
3 5
Sample Output
Case #1: 6
Case #2: 5
题意:给你a,b两个数,然后从第三个开始,每个数都是前两个数的差的绝对值,问这个序列中有多少个不同的元素。
分析:一开始以为直接暴力,最后肯定会有一个数变为0。直接暴力,用set求元素个数。但a,b的范围太大,所以wa了一发。其实这有点辗转相除的思想,假设a>b,所以后面的序列就有a/b个数,最后剩下a%b这个数,然后再比较a%b,b这两个数,最后能直接除尽的话说明能刚好出现0,所以加上a/b+1个数就行了。同时,还得注意特殊情况,就是a,b为零是情况,在这里又wa了一次。。。
代码:
#include<iostream> #include<string> #include<cstdio> #include<cstring> #include<vector> #include<math.h> #include<map> #include<set> #include<queue> #include<algorithm> using namespace std; const int inf = 0x3f3f3f3f; void f(long long a,long long b,long long &ans){ //判别a,b是否为0 if (a==0&&b==0) { ans+=1; return; } if ((a==0&&b!=0)||(a!=0&&b==0)){ ans+=2; return; } if (a>b){ if (a%b==0){//是否能整除 ans+=(a/b+1); return ; } ans+=a/b; f(a%b,b,ans); } else { if (b%a==0){ ans+=(b/a+1); return ; } ans+=(b/a); f(b%a,a,ans); } } int main () { long long a,b; int t; int cnt=1; scanf ("%d",&t); while (t--){ scanf ("%lld%lld",&a,&b); long long ans=0; f(a,b,ans); printf ("Case #%d: %lld\n",cnt++,ans); } return 0; }
相关文章推荐
- UVALive 7045 Last Defence(找规律)
- 文章标题 UVALive 6062:Reduce the Maintenance Cost(双联通分量缩点)
- 文章标题 UVALive 4670 : Dominating Patterns (AC自动机模板题)
- 文章标题UVALive 6424:Russian Dolls(贪心)
- 文章标题 UVALive 7035: Built with Qinghuai and Ari Factor(水)
- UVALive7045 Last Defence(GCD思想)
- Last Defence - UVA7045
- 文章标题 UVALive 7740 : Coding Contest (费用流+精度)
- 文章标题 UVALive 6432 Influence(dfs)
- UVALive7045 多少个不同的数
- 文章标题 CSU 1845: Sensor network (暴力LCA+kruskal思想)
- Uvalive 6471 Triangle Count Sequences of Polygon Triangulations 多边形三角剖分 递归思想
- 文章标题 UVA 12299 : RMQ with Shifts(线段树+点修改)
- 文章标题 HDU 2489 : Minimal Ratio Tree (最小生成树+状态压缩二进制思想)
- UVALive 5695 -The Last Puzzle -区间dp
- UVALive6662 The Last Ant
- 【UVAlive】康托展开的思想
- 【找规律】UVALive - 7045 Last Defence
- UVALive 7045 Last Defence(2014西安赛区现场赛)
- 文章标题 UVA 11374 : Airport Express(最短路--dijkstra)