P4549 【模板】裴蜀定理
题目描述:
给定一个包含 n个元素的整数序列 A,记作 A1,A2,A3,...,An。
求另一个包含 n 个元素的待定整数序列 XX,记 S=∑Ai×Xi(1<=i<=n),使得 S>0 且 S 尽可能的小。
思路:根据裴蜀定理,ax+by=c有解的情况是gcd(a,b)|c,而c的最小正数取值就是gcd(a,b),那可以扩展为
ax+by+cz=d有解的条件是gcd(a,b,c)|d吗,当然是可以的,于是乎就转换成了求n个整数的最大公约数,注意
负数要转换为正数求解.
AC代码:
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 10000005; const int inf = 0x3f3f3f3f; int gcd(int m, int n) { return n ? gcd(n, m % n) : m; } int main() { //freopen("test.txt", "r", stdin); int n;scanf("%d", &n); int ans; scanf("%d", &ans); ans = abs(ans); for (int i = 2; i <= n; i++) { int t; scanf("%d", &t); t = abs(t); ans = gcd(ans, t); } cout << ans << endl; return 0; }