CodeForces - 1311D Three Integers(暴力)

题目链接:点击查看

题目大意:给出三个数 a , b , c ,每次操作可以挑选任意一个数让其加一或减一,现在问最少需要操作多少次,可以使得:

  1. a 可以整除 b
  2. b 可以整除 c

题目分析:乍一看是一道数论题,但结合最优性剪枝的方法,我们可以写一个三层for循环的暴力,因为三个数初始时最大只有1e4,所以我们第一层for枚举 a ,第二层for枚举 b ,第三层for枚举 c ,直接暴力枚举肯定是不行的,1e12的复杂度,但在确定了a之后,因为b只能是a的倍数,所以第二层for的复杂度一下子就降下来了,同理第三层for的复杂度也不会太高,大概是nlognlogn?我猜的,反正不会很大,然后配合上最优性剪枝,就能轻松过题了

需要注意的是上限的确定问题,第一个上限是枚举 a 的上限,一开始我写的上限是 a + b + c ,结果WA了,一气之下改成了1e5就A了。。不过赛后被rj了,还是有点小难受的,这里就是第二个上限,也就是最终答案的上限了,最后初始化改成了无穷大就AC了,有时候比赛莽一点也未尝不是好事

代码:
 

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
using namespace std;
      
typedef long long LL;
     
typedef unsigned long long ull;
      
const int inf=0x3f3f3f3f;
 
const int N=2e5+100;
 
int main()
{
#ifndef ONLINE_JUDGE
//    freopen("input.txt","r",stdin);
//    freopen("output.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
	int w;
	cin>>w;
	while(w--)
	{
		int a,b,c;
		scanf("%d%d%d",&a,&b,&c);
		int ans=inf;
		int limit=1e5+100;
		int aa,bb,cc;
		for(int i=1;i<=limit;i++)
		{
			if(abs(a-i)>ans)
				continue;
			for(int j=1;j*i<=limit;j++) 
			{
				if(abs(a-i)+abs(b-j*i)>ans)
					continue;
				for(int k=1;k*j*i<=limit;k++)
				{
					if(ans>abs(a-i)+abs(b-j*i)+abs(c-j*i*k))
					{
						ans=abs(a-i)+abs(b-j*i)+abs(c-j*i*k);
						aa=i,bb=j*i,cc=j*i*k;
					}
				}
			}
		}
		printf("%d\n",ans);
		printf("%d %d %d\n",aa,bb,cc);
	}
     
     
     
     
     
     
     
     
     
     
     
     
     
    return 0;
}
发布了657 篇原创文章 · 获赞 22 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/104509221