牛客国庆集训派对Day1-C:Utawarerumono(数学)

链接:https://www.nowcoder.com/acm/contest/201/C
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 1048576K,其他语言2097152K
64bit IO Format: %lld

题目描述

算术是为数不多的会让Kuon感到棘手的事情。通常她会找Haku帮忙,但是Haku已经被她派去买东西了。于是她向你寻求帮助。
给出一个关于变量x,y的不定方程ax+by=c,显然这个方程可能有多个整数解。Kuon想知道如果有解,使得p_{2}x^{2}+p_{1}x+q_{2}y^{2}+q_{1}y最小的一组整数解是什么。为了方便,你只需要输出p_{2}x^{2}+p_{1}x+q_{2}y^{2}+q_{1}y的最小值。

输入描述:

第一行三个空格隔开的整数a,b,c(0 ≤ a,b,c≤ 105)。
第二行两个空格隔开的整数p1,p2(1 ≤ p1,p2 ≤ 105)。
第三行两个空格隔开的整数q1,q2(1 ≤ q1,q2 ≤ 105)。

输出描述:

如果方程无整数解,输出“Kuon”。
如果有整数解,输出的最小值。

示例1

输入

2 2 1
1 1
1 1

输出

Kuon

示例2

输入

1 2 3
1 1
1 1

输出

4

思路

先利用GCD来判断不定方程ax+by=c是否有解,如果有解,将不定方程和带入方程p_{2}x^{2}+p_{1}x+q_{2}y^{2}+q_{1}y进行化简;

过程如下:

y=dfrac {c-ax}{b}

将y带入方程可得:

p_{2}x^{2}+p_{1}x+q_{2},dfrac {c^{2}+a^{2}x^{2}-2acx}{b^{2}}+q_{1}dfrac {c-ax}{b}

=left( p_{2}+dfrac {a^{2}q_{2}}{b^{2}}
ight) x^{2}+left( p_{1}-dfrac {2acq_{2}}{b^{2}}-dfrac {aq_{1}}{b}
ight) x+dfrac {q_{2}c^{2}}{b^{2}}+dfrac {q_{1}c}{b}

由抛物线的性质可知:方程p_{2}x^{2}+p_{1}x+q_{2}y^{2}+q_{1}y的最小值在对称轴附近

由上式化简可知,抛物线的对称轴为:dfrac {dfrac {q_{1}a}{b}+dfrac {2acq_{2}}{b^{2}}-p_{1}}{2left( p_{2}+dfrac {a^{2}}{b^{2}}q_{2}
ight) }

然后在这条抛物线两边来找满足ax+by=c的整数解就可以了(即满足left( c-ax
ight) \% b=0),然后求两边满足要求的最小解就可以了

AC代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <string>
#define ll long long
#define ull unsigned long long
#define ms(a) memset(a,0,sizeof(a))
#define pi acos(-1.0)
#define INF 0x7f7f7f7f
#define lson o<<1
#define rson o<<1|1
const double E=exp(1);
const int maxn=1e6+10;
const int mod=1e9+7;
using namespace std;
ll gcd(ll a,ll b)
{
	return b?gcd(b,a%b):a;
}
int main(int argc, char const *argv[])
{
	ios::sync_with_stdio(false);
	ll a,b,c;
	ll p1,p2;
	ll q1,q2;
	cin>>a>>b>>c;
	cin>>p1>>p2;
	cin>>q1>>q2;
	ll _=gcd(a,b);
	if(c%_)
		cout<<"Kuon"<<endl;
	else
	{
		ll x=((2*a*c*q2)/(b*b)+a*q1/b-p1)/(2*(p2+(a*a*q2)/(b*b)));
		ll x1=x,x2=x;
		while((c-a*x1)%b)
			x1--;
		while((c-a*x2)%b)
			x2++;
		ll a1=(c-a*x1)/b;
		ll a2=(c-a*x2)/b;
		ll res1=(p1*x1+p2*x1*x1+q2*a1*a1+q1*a1);
		ll res2=(p1*x2+p2*x2*x2+q2*a2*a2+q1*a2);
		cout<<min(res1,res2)<<endl;
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Friends-A/p/10324349.html