若两个数非互素则加入一个数使之满足条件,最后输入序列。
思路:本来是枚举两个数的公约数往上递增判断其是否分别与这两个
数互素,结果错了,后来当不满足条件时,直接往两个数之间
加入 1 即可,因为 1 与任何数互素。
代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <cmath>
#include <utility>
#include <algorithm>
using namespace std;
#define N 1020
#define inf 0x3f3f3f3f
int num[N], ans[2*N];
int gcd(int a, int b)
{
int tmp;
while (a%b){
tmp = a;
a = b;
b = tmp%b;
}
return b;
}
int main()
{
#ifdef OFFLINE
freopen("t.txt", "r", stdin);
#endif
int i, j, k, n, m, t, x;
while (~scanf("%d", &n))
{
t = x = 0;
for (i = 0; i < n; i++){
scanf("%d", &num[i]);
}
for (i = 0; i < n - 1; i++){
if (gcd(num[i], num[i + 1]) == 1){
ans[x++] = num[i];
}
else{
t++;
ans[x++] = num[i], ans[x++] = 1; //1 跟任何数都互素
}
}
ans[x++] = num[n - 1];
printf("%d\n%d", t, ans[0]);
for (i = 1; i < x; i++)
printf(" %d", ans[i]);
printf("\n");
}
return 0;
}
本文介绍了一种算法,用于将给定数组转换为互素数数组,即确保数组中任意两个相邻数的最大公约数为1。通过在不满足条件的数之间插入数字1来实现这一目标。
329

被折叠的 条评论
为什么被折叠?



