雪竹的天空

theorix

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  34 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks
简单的dp题
注意输出函数的编写
还有dp方程
  1/****************************************************************
  2    Problem: 1171
  3    User: theorix
  4    Language: C++
  5    Result: Accepted
  6    Time:152 ms
  7    Memory:980 kb
  8****************************************************************/

  9
 10#include<iostream>
 11#include<math.h>
 12using namespace std;
 13#define NN 5000
 14int ans[NN+9];
 15int mem[NN+9][2];
 16int xans[NN+9];
 17int xmem[NN+9][2];
 18int chose[NN+9];
 19void output2(int n)
 20{
 21    if(xmem[n][0]==0)
 22    {
 23        int i;
 24        for(i=1;i<=n;i++)
 25            printf("|");
 26        return ;
 27    }

 28    output2(xmem[n][0]);
 29    printf("x");
 30    output2(xmem[n][1]);
 31}

 32void output(int n)
 33{
 34    if(chose[n]==0)
 35    {
 36        for(int i=1;i<=n;i++)
 37            printf("|");
 38    }

 39    else if(chose[n]==1)
 40    {
 41        output(mem[n][0]);
 42        printf("+");
 43        output(mem[n][1]);
 44    }

 45    else if(chose[n]==2)
 46    {
 47        output2(mem[n][0]);
 48        printf("x");
 49        output2(mem[n][1]);
 50    }

 51}

 52int main()
 53{
 54//    freopen("toothpicks.in","r",stdin);
 55//    freopen("out.txt","w",stdout);
 56    int i,j,k,n,t,tt;
 57    xans[1]=1;
 58    for(i=2;i<=NN;i++)
 59    {
 60        t=(int)sqrt(i);
 61        xans[i]=i;
 62        for(j=2;j<=t;j++)
 63        {
 64            if(i%j==0&&xans[j]+xans[i/j]+2<xans[i])
 65            {
 66                xans[i]=xans[j]+xans[i/j]+2;
 67                xmem[i][0]=j;
 68                xmem[i][1]=i/j;
 69            }

 70        }

 71    }

 72    ans[1]=1;
 73    chose[1]=0;
 74    for(i=2;i<=NN;i++)
 75    {
 76        t=(int)sqrt(i);
 77        ans[i]=i;
 78        chose[i]=0;
 79        for(j=1;j<=i/2;j++)
 80        {
 81            if(ans[j]+ans[i-j]+2<ans[i])
 82            {
 83                ans[i]=ans[j]+ans[i-j]+2;
 84                mem[i][0]=j;
 85                mem[i][1]=i-j;
 86                chose[i]=1;
 87            }

 88        }

 89        for(j=2;j<=t;j++)
 90        {
 91            if(i%j==0&&xans[j]+xans[i/j]+2<=ans[i])
 92            {
 93                ans[i]=xans[j]+xans[i/j]+2;
 94                mem[i][0]=j;
 95                mem[i][1]=i/j;
 96                chose[i]=2;
 97            }

 98        }

 99    }

100//for(i=1;i<=160;i++)cout<<i<<" "<<chose[i]<<endl;
101//    for(n=1;n<=NN;n++)
102    while(scanf("%d",&n)!=EOF)
103    {//printf("%d\n",n);
104        printf("%d toothpicks: ",ans[n]);
105        output(n);
106        printf("=%d\n",n);
107    }

108}

109
posted on 2008-09-06 21:04 雪竹的天空( theorix ) 阅读(476) 评论(0)  编辑 收藏 引用 所属分类: 解题报告

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理