Last Defence (run time error)

本文详细解析了LastDefence算法的实现过程,针对给定的两个整数A和B,生成序列并计算序列中不同数字的数量。通过分析序列的周期性特征,优化算法避免冗余计算,最终提供了一个高效解决方案。
Last Defence
时间限制:1000 ms | 内存限制:65535 KB
描述
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 .
输入
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 ≤ 10^18).
输出
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 .
样例输入
2
7 4
3 5
样例输出
Case #1: 6
Case #2: 5
来源
Yougth
我的思路:首先这道题run time error了。。任何两个数,进行题中的运算,得出是一组数,最后肯定是x, x,0,x,x,0,x,x,0……循环的,所以当遇到x,x,0时候就停止,然后把前面的数和x,0进行处理,计算一下一共有多少不同的数。。希望大家帮看一下,这个代码运行没有错误,结果也对。
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<cmath>
using namespace std;
int a[10000000];
int main()
{
int T,i,j;
int g=1;
long long A,B;
cin>>T;
while(T--)
{
scanf("%lld%lld",&A,&B);
a[0]=A;
a[1]=B;
i=2;
while(1)
{
a[i]=fabs(a[i-1]-a[i-2]);
a[i+1]=fabs(a[i]-a[i-1]);
a[i+2]=fabs(a[i+1]-a[i]);
if(a[i]==a[i+1]&&a[i+2]==0)
{  a[i+1]=0;
break;
}
i++;
}
int n=i+2;
sort(a,a+i+2);
for(i=0;i<n-1;i++)
{
if(a[i]==a[i+1])
{
for(j=i;j<n-1;j++)
a[j]=a[j+1];
i--;
n--;
}
}
printf("Case #%d: %d\n",g,n);
g=g+1;
}
return 0;
}

 


转载于:https://www.cnblogs.com/NYNU-ACM/p/4236879.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值