Educational Codeforces Round 11A. Co-prime Array 数学
地址:http://codeforces.com/contest/660/problem/A
題目:
A. Co-prime Array time limit per test 1 second memory limit per test 256 megabytes input standard input output standard outputYou are given an array of?n?elements, you must make it a co-prime array in as few moves as possible.
In each move you can insert any positive integral number you want not greater than?109?in any place in the array.
An array is co-prime if any two adjacent numbers of it are co-prime.
In the number theory, two integers?a?and?b?are said to be co-prime if the only positive integer that divides both of them is?1.
InputThe first line contains integer?n?(1?≤?n?≤?1000) — the number of elements in the given array.
The second line contains?n?integers?ai?(1?≤?ai?≤?109) — the elements of the array?a.
OutputPrint integer?k?on the first line — the least number of elements needed to add to the array?a?to make it co-prime.
The second line should contain?n?+?k?integers?aj?— the elements of the array?a?after adding?k?elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array?a?by adding?kelements to it.
If there are multiple answers you can print any one of them.
Example input 32 7 28 output 1
2 7 9 28
?思路:互質是兩個數的最大公約數為1,即gcd(a,b)=1;
如果相鄰兩個數不是互質的話,插個1就好了(比賽時沒想到1,插得是1—100內某一質數,(因為x<10^9,所以100內的質數絕對可以,因為乘積大于最大取值范圍了)
代碼:
?
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 #include <cmath> 5 #include <cstring> 6 #include <queue> 7 #include <stack> 8 #include <map> 9 #include <vector> 10 11 #define PI acos((double)-1) 12 #define E exp(double(1)) 13 using namespace std; 14 15 int a[1010]; 16 int b[5000]; 17 int prime[17] = { 0,7,13,19,23,31,37,41,43,47,53,59,61,67,71,73,79 }; 18 19 int is_coprime(int a, int b) 20 { 21 int t = 1; 22 while (t) 23 { 24 if (b == 1) 25 return 1; 26 t = a %b; 27 a = b; 28 b = t; 29 } 30 return 0; 31 } 32 33 int main(void) 34 { 35 int n, k; 36 while (scanf("%d", &n) == 1) 37 { 38 k = 1; 39 memset(b, 0, sizeof(b)); 40 for (int i = 1; i <= n; i++) 41 scanf("%d", &a[i]); 42 for (int i = 1; i<n; i++) 43 { 44 if (is_coprime(a[i], a[i + 1])) 45 { 46 b[k++] = a[i]; 47 } 48 else 49 { 50 b[k++] = a[i]; 51 for (int j = 1; j <= 16; j++) 52 if (is_coprime(a[i], prime[j]) && is_coprime(a[i + 1], prime[j])) 53 { 54 b[k++] = prime[j]; 55 break; 56 } 57 } 58 } 59 b[k] = a[n]; 60 cout << k - n << endl; 61 for (int i = 1; i<k; i++) 62 printf("%d ", b[i]); 63 printf("%d\n", b[k]); 64 } 65 return 0; 66 } View Code?
轉載于:https://www.cnblogs.com/weeping/p/5371872.html
總結
以上是生活随笔為你收集整理的Educational Codeforces Round 11A. Co-prime Array 数学的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ZOJ2314 Reactor Cool
- 下一篇: Spark系列(八)Worker工作原理