題目描述
給出n個數(A1...An)現求一組整數序列(X1...Xn)使得S=A1X1+...AnXn>0,且S的值最小
輸入輸出格式
輸入格式:
第一行給出數字N,代表有N個數 下面一行給出N個數
輸出格式:
S的最小值
輸入輸出樣例
說明
對於100%的數據,1 \le n \le 201≤n≤20,|x_i| \le 100000∣xi∣≤100000
裴蜀(貝祖)定理
ax + by = c 有整數解 x y 的條件是 c 是 gcd(a,b) | c , 所以 c 爲最小正整數的話就是要求 c 是a b 的最大公約數。
這個定理對於多個變量來說同樣使用。可以看成兩個變量的不斷累加。
但是要注意輸入的數可能是負數,此時直接取反就可以了,對gcd沒有影響。
代碼
#include<cstdio> #include<cstdlib> #include<cstring> #include<string.h> #include<cmath> #include<algorithm> #include<queue> #include<stack> #include<deque> #include<map> #include<iostream> using namespace std; typedef long long LL; const double pi=acos(-1.0); const double e=exp(1); const int N = 998244353; int gcd(int a, int b) { int mid; while(b) { mid = a; a = b; b = mid % b; } return a; } int main() { int i,p,j,n,t; scanf("%d",&n); scanf("%d",&p); if(p < 0) p = -p; for(i = 1; i < n; i++) { scanf("%d",&j); if(j < 0) j = -j; p = gcd(p,j); } printf("%d\n",p); return 0; }