Problem Description
We will consider a linear Diaphonic equation here and you are to find out whether the equation is solvable in non-negative integers or not.
Easy, is not it?
Easy, is not it?
Input
There will be multiple cases. Each case will consist of a single line expressing the Diophantine equation we want to solve. The equation will be in the form ax + by = c. Here a and b are two positive integers expressing the co-efficient of two variables x and y.
There are spaces between:
1. “ax” and ‘+’
2. ‘+’ and “by”
3. “by” and ‘=’
4. ‘=’ and “c”
c is another integer that express the result of ax + by. -1000000<c<1000000. All other integers are positive and less than 100000. Note that, if a=1 then ‘ax’ will be represented as ‘x’ and same for by.
There are spaces between:
1. “ax” and ‘+’
2. ‘+’ and “by”
3. “by” and ‘=’
4. ‘=’ and “c”
c is another integer that express the result of ax + by. -1000000<c<1000000. All other integers are positive and less than 100000. Note that, if a=1 then ‘ax’ will be represented as ‘x’ and same for by.
Output
You should output a single line containing either the word “Yes.” or “No.” for each input cases resulting either the equation is solvable in non-negative integers or not. An equation is solvable in non-negative integers if for non-negative integer value of x and y the equation is true. There should be a blank line after each test cases. Please have a look at the sample input-output for further clarification.
Sample Input
2x + 3y = 10 15x + 35y = 67 x + y = 0
Sample Output
Yes. No. Yes. HINT: The first equation is true for x = 2, y = 2. So, we get, 2*2 + 3*2=10. Therefore, the output should be “Yes.”
题目题意:题目题意很直白,就是让我们求是否存在满足要求的x,y(其中x与y都是非负数.
题目分析 :我们可以利用扩展欧几里得求出x与y的很多组解,但是我们又要满足题意(非负),我们注意到ax+by=c 求得了x,则y=(c-ax)/b,很明显y随x递减,也就是说,我们就一个x的极限(x为最小的正整数解),如果y>0 那么就满足,否则不满足,同理,y也可以。
代码里面有这里的注释!
#include<iostream>
#include<cstdio>
#include<cstring>
#define ll long long
using namespace std;
const int maxn=10000;
char str[maxn];
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if (b==0) {
x=1;
y=0;
return a;
}
ll r=exgcd(b,a%b,x,y);
ll t=x;
x=y;
y=t-a/b*y;
return r;
}
bool linear_equation(ll a,ll b,ll c,ll &x,ll &y)
{
ll d=exgcd(a,b,x,y);
if (c%d)
return false;
ll k=c/d,flag=0;
x=x*k,y=y*k;//求得一组解x y
ll t=b/d;//x的周期t
x=(x%t+t)%t;//x的最小正整数
if ((c-a*x)/b>=0)//判断y
flag=1;
t=a/d;//y的周期t
y=(y%t+t)%t;//y的最小正整数
if ((c-b*y)/a>=0)//判断x
flag=1;
if (flag)
return true;
else
return false;
}
int main()
{
while (gets(str)!=NULL) {
ll a=0,b=0,c=0,i,j,k,x,y;
for ( i=0;str[i]!='x';i++)
a=a*10+str[i]-'0';
for ( j=i+4;str[j]!='y';j++)
b=b*10+str[j]-'0';
for (k=j+4;str[k]!='\0';k++)
c=c*10+str[k]-'0';
if (a==0) a=1;
if (b==0) b=1;
if (linear_equation(a,b,c,x,y))
printf("Yes.\n\n");
else
printf("No.\n\n");
memset (str,0,sizeof (str));
}
return 0;
}