1. 程式人生 > >CF1025B Weakened Common Divisor

CF1025B Weakened Common Divisor

set turn log scanf col amp div int 滿足

思路:

首先選取任意一對數(a, b),分別將a,b進行因子分解得到兩個因子集合然後取並集(無需計算所有可能的因子,只需得到不同的質因子即可),之後再暴力一一枚舉該集合中的元素是否滿足條件。

時間復雜度:O(sqrt(amax) + n * log(amax))。

實現:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAXN = 150005;
 4 int a[MAXN], b[MAXN];
 5 set<int> factor(int x)
 6 {
 7     set<int> res;
8 for (int i = 2; i * i <= x; i++) 9 { 10 if (x % i == 0) 11 { 12 res.insert(i); 13 while (x % i == 0) x /= i; 14 } 15 } 16 if (x != 1) res.insert(x); 17 return res; 18 } 19 int main() 20 { 21 int n; 22 while (scanf("%d", &n) != EOF)
23 { 24 for (int i = 0; i < n; i++) scanf("%d %d", &a[i], &b[i]); 25 set<int>s1 = factor(a[0]); 26 set<int>s2 = factor(b[0]); 27 set<int> st; 28 for (auto it: s1) st.insert(it); 29 for (auto it: s2) st.insert(it); 30 for
(int i = 1; i < n; i++) 31 { 32 set<int> tmp; 33 for (auto it: st) 34 { 35 if (it > a[i] && it > b[i]) continue; 36 else if (a[i] % it && b[i] % it) continue; 37 tmp.insert(it); 38 } 39 st = tmp; 40 } 41 if (st.empty()) puts("-1"); 42 else printf("%d\n", *st.begin()); 43 } 44 return 0; 45 }

CF1025B Weakened Common Divisor