Problem F: Floor Plan

F Floor Plan
Via Gisela Giardino on flickr
You are an architect and you have just been appointed to
build a new swimming hall. The organisation behind these
plans has acquired funding for a swimming pool and surrounding building as large as they want, but unfortunately
they could not find anyone willing to pay for the floor surrounding the pool. They decided to pay for the floor tiles
out of their own pocket. Because this has already cost
them an arm and a leg, they want you to use all the floor
tiles in your proposed plan.
Being an architect, you care for aesthetics. You see it as
absolutely vital that both the swimming pool and the surrounding building are perfect squares. This raises an interesting problem: how can you make sure that the square shapes are guaranteed, while still
using all the floor tiles the organisation bought?
Given the number of tiles n, find the length of the side of the building m and and the length
of the side of the pool k such that n = m^2 − k^2
, or print impossible if no suitable m and k exist.
Input
• One line containing a single integer 1 ≤ n ≤ 1e9
.
Output
Print two non-negative integers m, k such that n = m2 −k
2
, or print impossible if no such
integers exist. If there are multiple valid solutions, you may output any one of them.
Sample Input 1 Sample Output 1
7 4 3
Sample Input 2 Sample Output 2
10 impossible
Sample Input 3 Sample Output 3
15 4 1

这道题的思路是n=m^2- k^2=(m+k)*(m-k),(m+k)与(m-k)是n的两个因子,他们两个相加为2m是可以被2整除的,m+k-m就等于k

#include<cstdio>
#include<iostream>
using namespace std;
int n;
bool ok;
int main(){
	scanf("%d",&n);
	for(int i=1;i*i<=n;i++){
		if(n%i!=0)
		continue;
		int x=n/i;
		int y=x+i;
		if(y%2==0){
			printf("%d %d\n",y/2,x-y/2);
			ok=true;
			break;
		}
	}
	if(!ok){
		cout<<"impossible"<<endl;
	}
	return 0;
}

另一种做法,是我比赛时误打误撞的,但前提也得是(m+k)*(m-k).
(m+k)为n,那么m-k就得是1,如果(m+k)是n/2,那么m-k就是2…
如果n是奇数,我们让k等于n/2(向下取整),那么m为n-k,恰巧m-k为1
如果n是偶数,n/2为奇数就不成立,为偶数就一定成立.
我是这么想的,n如果是偶数,那么m-k一定是偶数最少相差2,比如m为n/2+1,k为n-m一定等于n/2-1.要找出n/2的情况,把n/2分解为n/2/2+1与n/2/2-1的情况,他们俩相加为n/2,相减为2就满足题意了
比如20 ,除以2为10,把它分为4和6,他们相加为10,相差为2
比如10,除以2为5,那它就很难分了

#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
int n,m,k;
int main(){
	scanf("%d",&n);
	if(n%2!=0){
		int p=n/2;
		int q=n-p;
		printf("%d %d\n",q,p);
		return 0;
	}
	else{
			n/=2;
			if(n%2==0){
				n/=2;
				printf("%d %d\n",n+1,n-1);
				return 0;
			}
			else{
			printf("impossible\n");
			return 0;				
			}
	}
	return 0;
}
发布了115 篇原创文章 · 获赞 3 · 访问量 1764

猜你喜欢

转载自blog.csdn.net/qq_43721152/article/details/104886263