ZOJ 3846 GCD Reduce

来源:互联网 发布:音乐节 知乎 编辑:程序博客网 时间:2024/06/07 00:36

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3846

题意:给定一个长度为n的数列每次可以选个二元组(a[i],a[j])换成他们的最大公约数

然后问能不能在5*n次操作内把他们全部换成1,输出每次选择的是第几个与第几个数

解题思路:

因为每次操作都是换成GCD 因此n个数的最大公约数肯定为1,如果不为1的话肯定不能变成1的

然后随便构造一种方法就行了,从1到n搞两遍一定可以全变成1;总次数为2*(n-1)

If there are multiple answers, you canprint any of them.(理解这句话)

代码:

#include<iostream>#include<cstdio>using namespace std;int c[500005];int gcd(int x,int y){    int temp,r;    if(x<y)    {        temp=x;        x=y;        y=temp;    }    while((r=x%y)>0)    {        x=y;        y=r;    }    return y;}int main(){    int n;    int test=1;    while(scanf("%d",&n)!=EOF)    {        for(int i=0;i<n;i++)            scanf("%d",&c[i]);        int tmp=c[0];        for(int i=1;i<n;i++)            tmp=gcd(tmp,c[i]);            if(tmp!=1)        {            printf("Case %d: -1\n\n",test++);        }        else        {            printf("Case %d: %d\n",test++,2*(n-1));            for(int i=2;i<=n;i++)                printf("1 %d\n",i);            for(int i=2;i<=n;i++)                printf("1 %d\n",i);                printf("\n");        }    }    return 0;}


0 0