hdu 4982(贪心思想)

来源:互联网 发布:kismet windows 编辑:程序博客网 时间:2024/06/05 17:34

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 k1 numbers sums up to a square of integer.[/ol]
    For example, a set {1, 5, 6, 10} is a squary partition of 22 because1 + 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 integersn and k (2n200000,2k30).
     

    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 24 222 4
     

    Sample Output
    NOYESYES
    解题思路:首先很容易想到的是枚举完全平方数,接下来就是构造一个从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-1int z = y - 1; //第k-2个数为k-2int tot = t * t - sum; //距离目标和还差totif(tot < 0) continue;y += tot; //贪心的思想,先把k-1个数全部加上totif(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;}


    0 0