题解:先用等差和等比性质算出缺的一项值应为多少,然后先等差检测,检测是否为上升序列,每一项都要大于0小于1000000,
如果不行标记,进行等比检测,检测是否为上升序列,每一项都要大于0小于1000000,而且要检测公比是否为整数(用等比中项和相邻两项余数为0),最后输出。
Your younger sister is studying for an upcoming standardized test in mathematics. She needs practice
with the common style of problem in which the student is asked to fill in the missing value in a sequence
of numbers.
The vast majority of these problems feature either arithmetic sequences (where each number in the
sequence is formed by adding an integer constant to the prior number) or geometric sequences (where
each number in the sequence is formed by multiplying the prior number by an integer constant).
Write a program that will help your sister practice on this style of problem by allowing her to check
her answers on sample problems.
Input
Input will consist of one or more datasets.
Each dataset will be a single line containing 4 integers defining a sequence. One of these will be ‘
-1
’,
denoting the missing value. The remainder will be positive integers in the range 1..10,000, inclusive.
Other than the ‘
-1
’ placeholder value, the values will be in non-decreasing order.
End of input will be signaled by a line containing four ‘
-1
’ values.
Output
For each dataset, print one line of output.
If an integer in the range 1..1,000,000 inclusive exists that can be filled in to the missing value
position to create an arithmetic or geometric sequence, print that missing value.
If there is no such positive integer, print ‘
-1
’.
Sample Input
1 2 -1 4
2 4 8 -1
7 8 -1 21
5 -1 11 14
-1 2 4 6
-1 -1 -1 -1
Sample Output
3
16
-1
8
-1
代码:
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
using namespace std;
#include<queue>
#include<vector>
#include<stack>
#include<map>
typedef long long int LL;
#define MAX 100010
int main()
{
LL a[10],b[10],d,q,l,flag,i,j,k,kkk,kk;
while(scanf("%lld%lld%lld%lld",&a[0],&a[1],&a[2],&a[3])!=EOF)
{
flag=0;kkk=0;kk=0;
if(a[0]==-1&&a[1]==-1&&a[2]==-1&&a[3]==-1)
break;
for(i=0;i<4;i++)
b[i]=a[i];
if(a[0]==-1)
{
k=0;
a[0]=a[1]+a[2]-a[3];
b[0]=b[1]*b[2]/b[3];
}
if(a[1]==-1)
{
k=1;
a[1]=a[0]+a[3]-a[2];
b[1]=b[0]*b[3]/b[2];
}
if(a[2]==-1)
{
k=2;
a[2]=a[0]+a[3]-a[1];
b[2]=b[0]*b[3]/b[1];
}
if(a[3]==-1)
{
k=3;
a[3]=a[1]+a[2]-a[0];
b[3]=b[1]*b[2]/b[0];
}
d=a[1]-a[0];
if(d<0||a[0]<=0||a[0]>1000000)
kkk=1;
else
{
for(i=1;i<4;i++)
{
if(a[i]-a[i-1]!=d||a[i]<=0||a[i]>1000000)
{
kkk=1;
break;
}
}
}
if(kkk==1)
{
if(b[0]!=0)
{
q=b[1]/b[0];
if(q<=0||b[0]*q!=b[1])
flag=1;
}
else
flag=1;
if(flag==0)
{
for(i=1;i<4;i++)
if(b[i]<=0||b[i]>1000000)
flag=1;
if(flag==0)
{
if(b[1]*b[1]==b[0]*b[2]&&b[2]*b[2]==b[1]*b[3])
{
if(b[1]%b[0]==0&&b[2]%b[1]==0&&b[3]%b[2]==0)
kk=1;
}
}
}
}
if(kkk==0&&flag==0)
printf("%lld\n",a[k]);
else if(kkk==1&&kk==1&&flag==0)
printf("%lld\n",b[k]);
else
printf("-1\n");
}
return 0;
}