Codeforces Round #624 (Div. 3) D - Three Integers(枚举技巧)

题目链接

In one move, you can add +1 or −1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤C such that B is divisible by A and C is divisible by B.You have to answer t independent test cases.

Input
The first line of the input contains one integer t (1≤t≤100) — the number of test cases.The next t lines describe test cases. Each test case is given on a separate line as three space-separated integers a,b and c (1≤a≤b≤c≤104).

Output
For each test case, print the answer. In the first line print res — the minimum number of operations you have to perform to obtain three integers A≤B≤C such that B is divisible by A and C is divisible by B. On the second line print any suitable triple A,B and C.

1.题目大意:给出三个数a≤b≤c,现在每次可以将一个数+1或者-1,每次移动步数加一,但不能减到小于等于0。现在求若移动到c%b==0 && b%a==0最小的移动总步数

2.自己做了挺长时间,尝试了一下枚举,没做出来。求助网上,发现了一个极好的方法确实值得学习。我们知道,整除关系也是倍数关系,那么我们在素筛那里是如何处理每个确定是素数的倍数呢?每次加上这个数的大小!那么这时我们发现可以一个三重循环,第一层i暴力到数的最大范围,第二层j每次增加i,第三层k每次增加j,这样保证了整除关系的三个数的枚举,再维护一个最小值即可

3.注意数的范围要比10000大一些,第一次10010WA了,第二次11000就过了

代码:

#include <iostream>
#include <math.h>
using namespace std;
#define INF 0x3f3f3f3f
const int maxn=11000;

int a,b,c,t;
int main()
{
    int x,y,z,ans,res;
    scanf("%d",&t);
    while(t--){
        scanf("%d%d%d",&x,&y,&z);
        ans=INF;
        for(int i=1;i<=maxn;i++)
            for(int j=i;j<=maxn;j+=i)
                for(int k=j;k<=maxn;k+=j){
                    res=abs(i-x)+abs(j-y)+abs(k-z);
                    if(res<ans){
                        ans=res;
                        a=i,b=j,c=k;
                    }
                }
        printf("%d\n",ans);
        printf("%d %d %d\n",a,b,c);
    }
    return 0;
}

发布了128 篇原创文章 · 获赞 7 · 访问量 5275

猜你喜欢

转载自blog.csdn.net/qq_44691917/article/details/104539224