Goffi and Squary Partition
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
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
Input
n and k ( 2≤n≤200000,2≤k≤30).
Output
n to k
Sample Input
2 2 4 2 22 4
Sample Output
NO YES YES
解题思路:首先很容易想到的是枚举完全平方数,接下来就是构造一个从1-k-1的等差数列,然后根据贪心的思想去调整数列的值。
这道题看似简单,其实很多坑,debug了好多次才AC。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
bool solve(int n,int k)
{
for(int t = 1; t * t < n; t++)
{
int x = n - t * t; //Xk的值
int cnt = 1,sum = 0;
for(int i = 1; i < k; i++)
{
if(cnt == x) cnt++;
sum += cnt;
cnt++;
}
if(cnt == k) //此时的前k-1个数的和sum=k*(k-1)/2,保持着等差数列
{
int y = cnt - 1; //第k-1个数为k-1
int z = y - 1; //第k-2个数为k-2
int tot = t * t - sum; //距离目标和还差tot
if(tot < 0) continue;
y += tot; //贪心的思想,先把k-1个数全部加上tot
if(y != x) return true; //如果此时第k-1个数不等于第k个数x,则说明符合要求
else if(z + 1 < y - 1) return true; //如果等于的话,把y减掉1,加到z上。
}
else if(cnt > k && sum + x <= n) return true;
}
return false;
}
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
if(solve(n,k))
printf("YES\n");
else printf("NO\n");
}
return 0;
}