您的位置:首页 > 编程语言 > Go语言

hdu 4982 Goffi and Squary Partition(思路)

2016-07-01 19:44 453 查看


Goffi and Squary Partition

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 1185 Accepted Submission(s): 404



Problem Description

Recently, Goffi is interested in squary partition of integers.

A set X of k distinct
positive integers is called squary partition of n if
and only if it satisfies the following conditions:

[ol]

the sum of k positive
integers is equal to n

one of the subsets of X containing k−1 numbers
sums up to a square of integer.[/ol]

For example, a set {1, 5, 6, 10} is a squary partition of 22 because 1 + 5 + 6 + 10 = 22 and 1 + 5 + 10 = 16 = 4 × 4.

Goffi wants to know, for some integers n and k,
whether there exists a squary partition of n to k distinct
positive integers.

Input

Input contains multiple test cases (less than 10000). For each test case, there's one line containing two integers n and k (2≤n≤200000,2≤k≤30).

Output

For each case, if there exists a squary partition of n to k distinct
positive integers, output "YES" in a line. Otherwise, output "NO".

Sample Input

2 2
4 2
22 4


Sample Output

NO
YES
YES


题意:给你n和k,问存不存在k个不同的正数之和为n,且这k个数里有k-1个数之和为某个整数的平方

思路:直接去找k个数组成n的所有可能肯定不行,所以我们可以从逆向考虑问题。我们先把≤200000的平方数都存下来,然后枚举平方数即可。

只要平方数可以由k-1个数组成,并且n-平方数不等于这k-1个数中的任何一个即可。

那么我们如何判断存不存在k-1个不等于n-平方数的数能组成这个平方数呢?(比如22=1+5+6+10,其中1+5+10=16=4²,那么我们枚举到4²时,组成16的三个数中不能有22-16=6)

我们假设n-平方数等于nn吧

显然,当k-1<nn时,我们至少能找到一个组合1+2+..+k-1满足条件,并且一定不会出现nn。

是这样吗?答案是不是。 当nn-(k-1)==1并且平方数-(1+2+...+(k-1))==1的时候依然是不满足的,比如k-1=4,nn=5,平方数为11 那么只有一种可能1+2+3+5=11 此时是从1+2+3+4变化而来,只能让最大的一个数+1,那么就会变成nn,所以此时也是不合法的。

当k-1>=nn就比较好处理了,我们可以想象至少的情况是1+2+...+(nn-1)+(nn+1)+...+k,我们只需要把平方数减去k-nn再判断可不可行即可~(相当于跳过nn,然后用k去替代nn)

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int a[500],cnt;
void init()
{
cnt=0;
for(int i=1;; i++)
{
if(i*i>200000) break;
a[cnt++]=i*i;
}
}
int main()
{
init();
int n,m;
while(~scanf("%d %d",&n,&m))
{
m--;
int flag=0;
for(int i=0; i<cnt; i++)
{
if(a[i]>=n) break;
if(a[i]<(m*m+m)/2) continue;
int k=n-a[i];
if(m>=k)
{
int l=m-k+1;
int b=a[i]-l;
if(b<(m*m+m)/2) continue;
}
else if(k-m==1&&k-m==a[i]-(m*m+m)/2) continue;
flag=1;
break;
}
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: