對於從1到N的連續整數集合,能劃分成兩個子集合,且保證每個集合的數字和是相等的。

來源:互聯網
上載者:User

#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;

const int Max=10000;

class DynamicClass
{
private:
 int n;  //n表示{1,2,3,...n}
 long s; //表示1+2+...+n
 vector<int>v; //v[i]表示累加和是i的組合數,如v[3]=2表示{1,2},{3}兩種組合
public:
 DynamicClass();
 void Divide(int &num); //num表示有多少種分法
};

DynamicClass::DynamicClass()
{
 int x;
 cout<<"請輸入N:";
 cin>>x;
 if(!cin.good())
 {
  cerr<<"輸入格式錯誤!"<<endl;
  exit(0);
 }
 if(x>=Max || x<=0)
 {
  cerr<<"輸入的值應該在0到"<<Max<<"之間!"<<endl;
  exit(0);
 }
 this->n=x;
 this->s=n*(n+1)/2;
 if(s%2)
 {
  cerr<<"不能劃分成值相等的兩個子集合!"<<endl;
  exit(0);
 }
 int i;
 for(i=0;i<=s;i++) this->v.push_back(0);
 this->v[0]=1; //很重要
}

void DynamicClass::Divide(int &num)
{
 int i,j;
 int k=s/2; //k是每個子集合所有值之和
 for(i=1;i<=this->n;i++) //將第1,2,...n個元素依次取出
 {
  for(j=k;j>=i;j--)
  {
   this->v[j]+=this->v[j-i]; //動態規劃,後一階段取決於前一階段
  }
  for(int t=1;t<=k;t++) cout<<this->v[t]<<" ";
  cout<<endl;
 }
 num=this->v[k]/2;
}

void main()
{
 DynamicClass dc;
 int num=0;
 dc.Divide(num);
 cout<<"有"<<num<<"種分法"<<endl;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.