ZOJ 3753 - Simple Equation (数论)

版权声明:是自己手打的没错 https://blog.csdn.net/Mr_Treeeee/article/details/82874372

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3753

题意:

给你A,B,M.

找出满足AX + BY = XY的X,Y。条件X>=M,在X+Y最小的前提下 X最小。

POINT:

变形得 (X-B)*(Y-A)=A*B

AB已知,求x+y最小,就是求x-b+y-a最小。

x-b和y-a明显是a*b的因子。

所以DFS,分解A*B的质因子即可。

扫描二维码关注公众号,回复: 3500422 查看本文章
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <map>
using namespace std;
#define LL long long
const LL inf = 0x3f3f3f3f3f3f3f3f;
LL A,B,M;
map<LL,LL> mp;

void f(LL x)
{
	for(LL i=2;i<=sqrt(x);i++){
		if(x%i==0){
			while(x%i==0){
				mp[i]++;
				x/=i;
			}
		}
	}
	if(x>1){
		mp[x]++;
	}
}
LL ans;
LL ax,ay;
LL limit;

void ff(LL x,LL y)
{
	if(x>=M){
		if(x+y<ans){
			ans=x+y;
			ax=x;ay=y;
		}else if(x+y==ans&&x<ax){
			ax=x;ay=y;
		}
	}
}

void dfs(LL now,map<LL,LL>::iterator it)
{
	LL a,b;
	a=now;
	b=A*B/a;
	ff(a+B,b+A);
	ff(b+B,a+A);

	if(now>limit) return;
	if(it!=mp.end()){
		LL p = 1;
		for(int i=0;i<=it->second;i++){
			dfs(now*p,++it);
			it--;
			p=p*it->first;
		}
	}
}



int main()
{
	while(~scanf("%lld%lld%lld",&A,&B,&M)){
		ans=inf;
		limit=sqrt(A*B);
		mp.clear();
		f(A);f(B);
		map<LL,LL>::iterator it;
		dfs(1LL,mp.begin());
		if(ans!=inf){
			printf("%lld %lld\n",ax,ay);
		}else{
			printf("No answer\n");
		}
	}

}

猜你喜欢

转载自blog.csdn.net/Mr_Treeeee/article/details/82874372