Codeforces Round #451 (Div. 2) B. Proper Nutrition

B. Proper Nutrition

time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output

Description

Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.

Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles.

In other words, you should find two non-negative integers x and y such that Vasya can buy x bottles of Ber-Cola and y Bars bars and x·a + y·b = n or tell that it's impossible.

Input

First line contains single integer n (1 ≤ n ≤ 10 000 000) — amount of money, that Vasya has.

Second line contains single integer a (1 ≤ a ≤ 10 000 000) — cost of one bottle of Ber-Cola.

Third line contains single integer b (1 ≤ b ≤ 10 000 000) — cost of one Bars bar.

Output

If Vasya can't buy Bars and Ber-Cola in such a way to spend exactly n burles print «NO» (without quotes).

Otherwise in first line print «YES» (without quotes). In second line print two non-negative integers x and y — number of bottles of Ber-Cola and number of Bars bars Vasya should buy in order to spend exactly n burles, i.e. x·a + y·b = n. If there are multiple answers print any of them.

Any of numbers x and y can be equal 0.


Solution

考试的时候看错题,以致于耽误太长时间,我把数据范围看成 \(10^9\) 了。
\(10^7\) 直接暴力枚举就过去了

对于更大数据的 \(O(logn)\) 算法如下:
题目要求是否有一组非负整数对 \(x,y\) 使得 \(ax+by=n\) 成立

首先,根据裴蜀定理,如果 \(gcd(a,b)\nmid n\) 显然不成立
\(a,b\) 满足上式的时候,可以使用拓展欧几里得先求出一组满足上式的整数解 \(x,y\)
此时,可以通过调整 \(x,y\) 的值使得 \(x,y\) 均非负,那么由下式,可以进行调整:

\[a(x+kb)+b(y-ka)=n \]

这样,我们得到

\[\begin{equation*} \begin{cases} x+kb\geq 0\\ y-ka\geq 0 \end{cases} \end{equation*} \]

进而

\[\begin{equation*} \begin{cases} k\geq -\frac{x}{b}\\ k\leq \frac{y}{a} \end{cases} \end{equation*} \]

所以,如果满足

\[\lceil -\frac{x}{b}\rceil \leq \lfloor\frac{y}{a}\rfloor \]

就说明有一组可行非负整数解
至于将这个解构造出来,直接将任意一个满足条件的 \(k\) 代入\(a(x+kb)+b(y-ka)=n\)即可

这相当于求不定方程非负整数解的通法吧,之前一直不知道怎么搞


#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

typedef long long LL;
LL costa,costb,n;

LL Extgcd(LL a,LL b,LL &x,LL &y){
	if(b==0){
		x=1;y=0;
		return a;
	}
	LL re=Extgcd(b,a%b,x,y);
	LL t=x;
	x=y;y=(t-(a/b)*y);
	return re;
}

int main(){
	scanf("%I64d%I64d%I64d",&n,&costa,&costb);
	LL x,y;
	LL gcd=Extgcd(costa,costb,x,y);
	if(n%gcd!=0){
		puts("NO");
		return 0;
	}
	LL tmp=n/gcd;
	x*=tmp;y*=tmp;
	if(x>=0 && y>=0){
		puts("YES");
		printf("%I64d %I64d\n",x,y);
		return 0;
	}
	if((x<0 && y<0)||(x<0 && y==0)||(x==0 && y<0)){
		puts("NO");
		return 0;
	}
	bool jud=LL(ceil(1.0*(-x)/costb))<=LL(floor(1.0*y/costa));
	if(jud){
		puts("YES");
		LL k=LL(ceil(1.0*(-x)/costb));
		x+=k*costb;
		y-=k*costa;
		printf("%I64d %I64d\n",x,y);
	}
	else puts("NO");
	return 0;
}
posted @ 2018-01-21 12:52  zzzc18  阅读(175)  评论(0编辑  收藏  举报