P4549 【模板】裴蜀定理

刷模板过300祭,我好弱啊!

简化题意:求\(a_1x_1+a_2x_2+...+a_nx_n\)的最小正值。

这道题要用到贝祖定理:对于一个不定方程\(ax+by=c\)\(x\)\(y\)有正整数解的充要条件是\(gcd(a,b)|c\)

显然对于多元的不定方程,这个东西也成立。

所以直接求这些系数的gcd,如果是负数的话取相反数就是了。

最小正值就是gcd嘛,所以直接就是了。

代码:


#include<cstdio>

int n, ans;

int gcd(int x, int y)
{
	return y == 0 ? x : gcd(y, x % y);
}
int main()
{
	scanf("%d", &n); scanf("%d", &ans);
	for(int i = 2; i <= n; i++)
	{
		int temp; scanf("%d", &temp);
		if(temp < 0) temp = -temp;
		ans = gcd(ans, temp);
	}
	printf("%d\n", ans);
	return 0;
}
posted @ 2018-09-20 13:33  Garen-Wang  阅读(123)  评论(0编辑  收藏  举报