ZOJ(3846)——GCD Reduce

此博客介绍了一种算法,用于将给定序列中的所有元素更改为1,通过选择两个元素并用它们的最大公约数替换,同时确保操作次数不超过5N。包括输入输出格式、示例解释和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given a sequence {A1, A2, ..., AN}. You task is to change all the element of the sequence to 1 with the following operations (you may need to apply it multiple times):

  • choose two indexes i and j (1 ≤ i < jN);
  • change both Ai and Aj to gcd(Ai, Aj), where gcd(Ai, Aj) is the greatest common divisor of Ai and Aj.

You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5N operations.

Input

Input will consist of multiple test cases.

The first line of each case contains one integer N (1 ≤ N ≤ 105), indicating the length of the sequence. The second line contains N integers, A1, A2, ..., AN (1 ≤ Ai ≤ 109).

Output

For each test case, print a line containing the test case number (beginning with 1) followed by one integer M, indicating the number of operations needed. You must assure that M is no larger than 5N. If you cannot find a solution, make M equal to -1 and ignore the following output.

In the next M lines, each contains two integers i and j (1 ≤ i < jN), indicating an operation, separated by one space.

If there are multiple answers, you can print any of them.

Remember to print a blank line after each case. But extra spaces and blank lines are not allowed.

Sample Input
4
2 2 3 4
4
2 2 2 2
Sample Output
Case 1: 3
1 3
1 2
1 4

Case 2: -1

这道题的大致意思就是:

给你一个从1~n的序列,然后你要选择两个下标i和j;然后对a[i]与a[j]进行求最大公约数,并把求出来的那个gcd去更新为a[i]与a[j]。

这里要注意输出的步骤并不是只有一种,比如说case1中的也可以不这样输出。

所以先对n个数求它们的最大公约数,若n个数的gcd为1的话,那么就说明全都能变成1,否则肯定不能变成1。

题目中又说最多的步数不能超过5*N,所以for两遍就可以了。

你想啊,因为n个数的gcd已经求出来为1了,所以后面肯定有1个数与第一个数的gcd为1的,若第一个突然与后面的一个数的gcd不是为1了,但是因为n个数的gcd为1,所以肯定有一个数与第一个数的gcd为1的,那么在第二次更新的时候,那么那个数就也会被更新为1。

这是一个很巧妙的方法,如果实在不能理解的话那么就自己举一组样例来看看好了,如:“2 4 3”,是不是更新了两次之后就全变成了1 1 1 了。

 

这里还用到了辗转相除法求最大公约数,注意这里最小公倍数的求法是两个数的乘积然后再除以gcd;

 

#include<stdio.h>
#include<string.h>
int gcd(int a,int b){
	if(a%b==0)  return b;
	else  return gcd(b,a%b);
}
int main(){
	int n,i,j;
	int a[100005];
	int k=1;
	while(~scanf("%d",&n)){
		memset(a,0,sizeof(a));
		for(i=1;i<=n;i++)
			scanf("%d",&a[i]);
		for(i=2;i<=n;i++){
			a[1]=gcd(a[1],a[i]);
		}
		if(a[1]!=1){
			printf("Case %d: -1\n",k);
		}
		else {
			printf("Case %d: %d\n",k,2*n-2);
			for(i=2;i<=n;i++)
				printf("1 %d\n",i);
			for(i=2;i<=n;i++)
				printf("1 %d\n",i);
		}
		k++;
		printf("\n");
	}
}


 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值