纪念一下自己不成熟的数论以及被模板牵制的思维
题意
给你 n , p , w , d n,p,w,d n,p,w,d,其中 d < w d < w d<w让你找出一个解 ( x , y , z ) (x,y,z) (x,y,z)满足下式 x ∗ w + y ∗ d = p x*w + y*d = p x∗w+y∗d=p x + y + z = n x + y + z = n x+y+z=n
分析与解答
解法1(弟弟板子法)
刚开始看到这个题,就感觉非常熟悉,直接百度了一下,发现时POJ2142的大数据版本,直接搜了一个板子,改了改就交https://blog.youkuaiyun.com/u013021513/article/details/47101057
因为之前的拓展欧几里得的板子没有考虑乘法会爆long long的情况,直接交上去会WA,结果到比赛结束才改好
/*************************************************************************
> File Name: 2019_10_13_3.cpp
> Author: z472421519
> Mail:
> Created Time: 2019年10月13日 星期日 17时46分57秒
************************************************************************/
#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#define ll long long
using namespace std;
void ex_gcd(ll a,ll b,ll &x,ll &y)
{
if(b == 1)
{
x = 1;
y = 1 - a;
}
else
{
ll x1,y1;
ex_gcd(b,a % b,x1,y1);
x = y1;
y = x1 - x * (a / b);
}
}
int main()
{
ll n,w,d,p;
cin >> n >> p >> d >> w;
ll gcd = __gcd(d,w);
ll x,y;
d /= gcd;
w /= gcd;
if(p == 0)
{
printf("0 0 ");
cout << n << endl;
return 0;
}
if(p % gcd != 0)
{
printf("-1\n");
return 0;
}
ex_gcd(d,w,x,y);
ll vx;
ll vy;
bool flag = false,flag1 = false;
/*在由x推导y的时候,p / gcd * x会爆long long,需要及时取模*/
vx = (((p / gcd % w) * (x % w)) % w + w) % w;
vy = (p / gcd - vx * d) / w;
if(vy < 0)
vy = -vy;
/*在由y推导x的时候,p / gcd * y会爆long long,需要及时取模*/
y = (((p / gcd % d) * (y % d)) % d + d) % d;
x = (p / gcd - w * y) / d;
if(x < 0)
x = -x;
if(x + y > vx + vy)
{
x = vx;
y = vy;
}
if(x + y > n || x * d + w * y != p / gcd)
printf("-1\n");
else
cout << x << " " << y << " " << n - x - y << endl;
}
解法2(cf官方解法)
对于这个题目,
z
z
z是没有条件限制的,因此只要有
x
+
y
<
=
n
x + y <= n
x+y<=n满足等式就行,注意到如果最小的
x
+
y
x + y
x+y都大于
n
n
n,那一定不行.
我们假设已经找到了一个满足条件的
(
x
,
y
)
(x,y)
(x,y),使得
x
∗
w
+
y
∗
d
=
p
x * w + y * d = p
x∗w+y∗d=p
当
y
>
w
y > w
y>w时,我们可以将
y
y
y减去w,再将该项与
x
∗
w
x * w
x∗w合并一下,也就是进行如下的过程:
x
∗
w
+
(
y
−
w
)
∗
d
+
w
∗
d
=
p
x * w + (y - w) * d + w * d = p
x∗w+(y−w)∗d+w∗d=p
(
x
+
d
)
∗
w
+
(
y
−
w
)
∗
d
=
p
(x + d) * w + (y - w) * d = p
(x+d)∗w+(y−w)∗d=p
此时等式的
x
1
+
y
1
=
x
+
d
+
y
−
w
x1 + y1 = x + d + y - w
x1+y1=x+d+y−w,因为d < w,所以
(
x
1
,
y
1
)
(x1,y1)
(x1,y1)是一个更优的解.以此类推,我们可以得到,所有最优的解的
y
y
y都小于
w
w
w,也就是说我们只要在
[
0
,
w
−
1
]
[0,w - 1]
[0,w−1]枚举y,再去计算x,判断是否满足条件即可.
/*************************************************************************
> File Name: codeforces_1244.cpp
> Author: z472421519
> Mail:
> Created Time: 2019年10月17日 星期四 15时24分02秒
************************************************************************/
#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#define ll long long
using namespace std;
int main()
{
ll n,p,d,w;
scanf("%lld%lld%lld%lld",&n,&p,&w,&d);
for(ll y = 0;y < w;y++)
{
if(p - d * y >= 0 && (p - d * y) % w == 0)
{
ll x = (p - d * y) / w;
if(x + y <= n)
{
printf("%lld %lld %lld\n",x,y,n - x - y);
return 0;
}
}
}
printf("-1\n");
return 0;
}