等长水管问题

来源:互联网 发布:淘宝达人帖子范例 编辑:程序博客网 时间:2024/04/27 15:34

现有一些水管,想拼接成两根相同长度的水管,求能拼出的最长长度。限制条件如下:水管长度为正整数,单根长度不超过1000,总长不超过1000,水管总根数不超过100.

例:5根水管,长度为1, 2 , 3 , 4 , 6.  由1 + 3 + 4 = 2 + 6, 最长长度为8.


#include <iostream>



using namespace std;


int main()
{
int n;
int len[100];
const int MAXLEN = 501;
int a[MAXLEN][MAXLEN] = {0};


cout << "please input the number of waterpipe:";
cin >> n;


cout << "please input the length of waterpipes:";
for (int i = 0; i < n; ++i) {
cin >> len[i];
}

a[0][0] = 1;


for (int i = 0; i < n; ++i)
for (int j = MAXLEN - 1; j >= 0; --j)
for (int k = MAXLEN - 1; k >= 0; --k)
if (a[j][k] == 1 || (j - len[i] >= 0 && a[j - len[i]][k] == 1) || (k - len[i] >= 0 && a[j][k - len[i]] == 1))
a[j][k] = 1;


for (int i = MAXLEN - 1; i >= 0; --i)
if (a[i][i] == 1) {
cout << "THe max length is :" << i << endl;
break;
}




return 0;
原创粉丝点击