水题也挺重要

标题:G、max | 时间限制:1 秒 | 内存限制:256M 
Give two positive integer c, n. You need to find a pair of integer (a,b) satisfy 1<=a,b<=n and the greatest common division of a and b is c.And you need to maximize the product of a and b 
 
输入描述: The first line has two positive integer c,n 
 
输出描述: Output the maximum product of a and b. 
 
If there are no such a and b, just output -1 
 
备注: 1<=c,n<=10^9 
 
示例 1

输入

2 4

输出


 
说明 a=2,b=4

题目大意:给出一个最小公约数c与n,从1-n中取2个数a,b要求a*b最大。

思路:签到水题,但是,我感觉这道水题体现出了我在思维上的缺点,个人做题风格偏向于莽汉,喜欢暴力,啥都想暴一发,wa后再思考........(这种作死的风格,比赛时还是能忍住的),但忍住不代表思维也能改变,我总是会优先想到暴力的方案,对于水题来说一般可行,但效率上以及正确率上都是不高,以该题为例,看完题的直接想法是枚举n范围内c的倍数取a,b找最大,也就是两层for,时间复杂度很大,nlogn?10^9耶....然而思考过的想法直接让a,b其中一个值等于n,然后再枚举找另一个值,该方法是可行的,但网上大佬直接判断就可得出答案,这可能就是差距吧,快一年了,还是喜欢暴力,总是对暴力抱以幻想,然而acm是搞算法啊........任重道远,修行尚浅,既然发现了那就从此改变..

暴力:

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
	long long int t,a,n,c,b,s=0,i,j;
	scanf("%lld%lld",&c,&n);
	if(n<c) printf("-1\n");
	else
	{
		for(i=1;i<=n/c;i++)
		{
			for(j=i;j<=n/c;j++)
			{
				s=max(s,i*c*j*c);
			}
		}
		printf("%lld\n",s);
	}
	return 0;
}

略思考:

#include<stdio.h>
int gcd(int a,int b)
{
	int r;
	while(b>0)
	{
		r=a%b;
		a=b;
		b=r;
	}
	return a;
}
int main()
{
	int c,n;
	scanf("%d%d",&c,&n);
	int x=n/c;
	long long sum1,sum2,sum;
	sum1=x*c;
	sum2=sum1;
	while(gcd(sum1,sum2)!=c)
	{
		sum2-=c;
		if(sum2<c)
		break;
	}
	if(sum1<c||sum2<c)
	printf("-1\n");
	else
	printf("%lld\n",sum1*sum2);
}

大佬的代码:

#include<stdio.h>
int main()
{
	long long int t,a,c,b;
	scanf("%lld%lld",&a,&b);
	c=b/a;
	t=c-1;
	if(c==1) printf("%lld",a*a);
	else if(t>0) printf("%lld",a*a*c*t);
	else printf("-1");
}
扫描二维码关注公众号,回复: 2648349 查看本文章

猜你喜欢

转载自blog.csdn.net/PleasantlY1/article/details/81380799
今日推荐