1099. Packing Passengers

这道题目,题意理解起来不是很难,但是使用常规的方法,一个个去试,在无解时很耗时间

依据数论的一些知识,

定理 3

如果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;
	}

}     


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值