nyoj 546(poj 1014)动态规划和dfs都可以,但是dfs 0ms通过

dfs代码:

#include<stdio.h>
#include<string.h>
int a[12],ff;
void dfs(int sum)
{
 if(sum==0){ ff=1;return ;}
 for(int i=10;i>=1;i--)//用较小的去匹配sum/2
 {
  if(sum>=i&&a[i]>0)
  {
   a[i]--;
   dfs(sum-i);
   
  }
 }
}
int main()
{
 int i,flag=0;
 while(1)
 {
  flag++;ff=0;
  memset(a,0,sizeof(a));
  int sum=0;
  for(i=1;i<=10;i++)
  {
   scanf("%d",&a[i]);
   if(a[i]==0) continue;
   sum+=i*a[i];
  }
  if(sum%2==1){printf("#%d:Can't be divided.\n\n",flag);continue;}
  if(sum==0)break;
  dfs(sum/2);
  if(ff)
   printf("#%d:Can be divided.\n\n",flag);
  else printf("#%d:Can't be divided.\n\n",flag);
 }
 return 0;
}          

动态规划代码:时间较长的算法

 
#include <stdio.h>
#include<string.h>
int c[60001];
int main()
{
    int i,j,sum,sum1,w,flag=0,a[10],b[60001];
    while(1)
    {
  flag++;
        sum=0;sum1=0;w=0;
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
  memset(c,0,sizeof(c));
        for(i=0;i<10;i++)
        {
            scanf("%d",&a[i]);
  // if(a[i]>=10)a[i]%=10;
   sum1+=a[i];
   if(a[i]%2==0)continue;
   for(int k=0;k<a[i];k++)
    c[w++]=i+1;
            sum+=a[i]*(i+1);
        }
  if(sum1==0)break;
  if(sum%2==1){printf("#%d:Can't be divided.\n\n",flag);continue;}
        for(i=0;i<w-1;i++)
        {
           for(j=sum/2;j>=c[i];j--)
           {
             b[j]=(b[j]>b[j-c[i]]+c[i])?b[j]:b[j-c[i]]+c[i];//用时比较多
           }
        }
  if(sum-2*b[sum/2]==0)
   printf("#%d:Can be divided.\n\n",flag);
  else printf("#%d:Can't be divided.\n\n",flag);
    }
 return 0;
}            

 

巧妙利用取模,多理解!

 
#include <stdio.h>
#include<string.h>
int main()
{
    int count=0,flag[60002];
 while(1)
 {
  int sum=0;
  memset(flag,0,sizeof(flag));
  flag[0]=1;
  for(int i=1;i<=10;i++)
  {
   scanf("%d",&flag[i]);
   sum+=i*flag[i];
   if(flag[i]%2==0)continue;
   flag[i]%=10;
   for(int j=1;j<=flag[i];j++)
   {
    for(int k=0;k<=sum;k++)
     if(flag[k]==1)
      flag[k+flag[i]]=1;
   }
  }
  count++;
  if(sum%2==1){printf("#%d:Can't be divided.\n\n",count);continue;}
  if(sum==0)break;
  if(flag[sum/2]==0)
   printf("#%d:Can't be divided.\n\n",count);
  else
   printf("#%d:Can be divided.\n\n",count);
 }
 return 0;
}       

 

你可能感兴趣的:(nyoj 546(poj 1014)动态规划和dfs都可以,但是dfs 0ms通过)