1205. 买不到的数目

题目链接

1205. 买不到的数目

题目描述

小明开了一家糖果店。

他别出心裁:把水果糖包成4颗一包和7颗一包的两种。

糖果不能拆包卖。

小朋友来买糖的时候,他就用这两种包装来组合。

当然有些糖果数目是无法组合出来的,比如要买 10 颗糖。

你可以用计算机测试一下,在这种包装情况下,最大不能买到的数量是17。

大于17的任何数字都可以用4和7组合出来。

本题的要求就是在已知两个包装的数量时,求最大不能组合出的数字。

输入格式

两个正整数 \(n,m\),表示每种包装中糖的颗数。

输出格式

一个正整数,表示最大不能买到的糖数。

数据范围

\(2≤n,m≤1000\)
保证数据一定有解。

输入样例:

4 7

输出样例:

17

解题思路

结论:如果 \(a,b\) 均是正整数且互质,那么由 \(ax+by,x≥0,y≥0\) 不能凑出的最大数是 \(ab−a−b\)
裴蜀定理:若a,b是整数,且GCD(a,b)=d,那么对于任意的整数x,y,ax+by都一定是d的倍数,特别地,一定存在整数x,y,使ax+by=d成立

假设 \(gcd(n,m)\neq 1\),则所有约数不为 \(gcd(n,m)\) 的数 \(n,m\) 都无法组合,反之如果 \(gcd(n,m)=1\),由裴蜀定理:存在整数 \((a,b)\) 使得 \(an+bm=1\),即 \(atn+btm=t\),即 \((at-m)n+(bt+n)m=t\),即可以使两个数平衡直觉上使其都为正整数,然后打表:
image
最后有如上结论

  • 时间复杂度:\(O(1)\)

代码

#include<cstdio>
using namespace std;
int n,m;
int main()
{
    scanf("%d %d",&n,&m);
    printf("%d",n*m-n-m);
    return 0;
}
  • 打表代码
// Problem: 买不到的数目
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1207/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

int n,m;
int dfs(int n,int m)
{
	for(int i=n*m;i;i--)
	{
		bool f=true;
		for(int j=0;j*n<=i;j++)
		{
			if((i-j*n)%m==0)
			{
				f=false;
				break;
			}
		}
		if(f)return i;
	}
}
int main()
{
    while(true)
    {
    	scanf("%d%d",&n,&m);
    	if(__gcd(n,m)!=1)continue;
    	printf("%d\n",dfs(n,m));
    }
    return 0;
}
posted @ 2022-02-09 18:45  zyy2001  阅读(47)  评论(0编辑  收藏  举报