这道题目,题意理解起来不是很难,但是使用常规的方法,一个个去试,在无解时很耗时间
依据数论的一些知识,
如果a和b是不都为0的任意整数,则gcd(a,b)是a与b的线性组合集合{ ax + by : x,y ∈Z}中的最小正元素。
那么如果一个数可以由a,b表示的话,那么这个数一定是gcd(a,b)的整数倍,所以在判断无解时,就比较快了
具体的代码如下
#include <iostream>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <stdio.h>
#include <math.h>
#include <list>
#include <stack>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
int gcd(int a, int b)
{
if(a ==0)
return b;
if(b==0)
return a;
if(b > a)
{
int temp = a;
a = b;
b = temp;
}
while(a%b != 0)
{
int r = a%b;
a = b;
b = r;
}
return b;
}
int main()
{
int n;
cin>>n;
int pa,ca;
int pb,cb;
double avga,avgb;
int numa=0,numb=0;
int times=0;
while(n!=0)
{
cin>>ca>>pa>>cb>>pb;
avga = ca*1.0/pa;
avgb = cb*1.0/pb;
times++;
cout<<"Data set "<<times<<": ";
int gcdpapb = gcd(pa,pb);
if(gcdpapb==0 || n % gcdpapb !=0 )
{
cout<<"cannot be flown"<<endl;
}
else if(fabs(avga-avgb)<1e-6 || avgb-avga >1e-6)
{
int temp=0;
while( temp<=n && (n-temp)%pa!=0)
{
temp += pb;
}
if(temp > n)
{
cout<<"cannot be flown"<<endl;
}
else
{
numb = temp/pb;
numa = (n-temp)/pa;
cout<<numa<<" aircraft A, "<<numb<<" aircraft B"<<endl;
}
}
else
{
int temp = 0;
while(temp <=n && (n-temp)%pb!=0)
{
temp += pa;
}
if(temp >n)
{
cout<<"cannot be flown"<<endl;
}
else
{
numa = temp/pa;
numb = (n-temp)/pb;
cout<<numa<<" aircraft A, "<<numb<<" aircraft B"<<endl;
}
}
cin>>n;
}
}