@zzzc18
2018-02-23T12:56:13.000000Z
字数 2367
阅读 1204
Codeforces
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.
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.
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.
考试的时候看错题,以致于耽误太长时间,我把数据范围看成 了。
直接暴力枚举就过去了
对于更大数据的 算法如下:
题目要求是否有一组非负整数对 使得 成立
首先,根据裴蜀定理,如果 显然不成立
当 满足上式的时候,可以使用拓展欧几里得先求出一组满足上式的整数解
此时,可以通过调整 的值使得 均非负,那么由下式,可以进行调整:
这样,我们得到
进而
所以,如果满足
就说明有一组可行非负整数解
至于将这个解构造出来,直接将任意一个满足条件的 代入即可
这相当于求不定方程非负整数解的通法吧,之前一直不知道怎么搞
#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;
}