【codechef】Alok-nath and His Sanskars(数字能不能被等分,记忆化深搜)

Input:
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
【codechef】Alok-nath and His Sanskars(数字能不能被等分,记忆化深搜)_第1张图片

http://www.codechef.com/problems/SANSKAR

#include<stdio.h>
int flag,n;
long long a[21],z;
int f[21];
void rec(int i,long long sum){ //记忆化深搜 
    int j,k;
    sum+=a[i];
    if(sum==z){
        flag=1;
        f[i]=1;
        return;
    }
    else if(sum>z){
        flag=0;
        return;
    }
    for(j=i+1;j<n;j++){
        if(!f[j]){
            rec(j,sum);
            if(flag==1){
            	f[i]=1;
                return;
            }
        }
    }
}
int main(){
    int t,i;
    long long k;
    scanf("%d",&t);
    while(t--){
        flag=0;
        z=0;
        scanf("%d%lld",&n,&k);
        for(i=0;i<n;i++){
             f[i]=0;
             scanf("%lld",&a[i]);
             z+=a[i];
        }
        if(z%k!=0){
            printf("no\n");
            continue;
        }
        else if(z==0){
            if(n>=k)
                printf("yes\n");
            else
                printf("no\n");  //这里注意 
            continue;
        }
        else{
            z/=k;
            for(i=0;i<k;i++){
                if(!f[i])
                    rec(i,0);
                if(!f[i])
                    break;
            }
        }
        if(i==k)
            printf("yes\n");
        else
            printf("no\n");
    }
    return 0;
}


你可能感兴趣的:(【codechef】Alok-nath and His Sanskars(数字能不能被等分,记忆化深搜))