c++ using classes

hello , im working on a program that tries to solve the partition problem: given n positive integers, partition them into two disjoint subsets with the same sum of
their elements. im supposed to implement a MySet class to do this and then use it to solve the problem. Ive completed the Myset class but problem is that i have no idea how do the next part. i dont understand how to use the MySet class to solve this. below are the actual instructions and what i have so far.

Your program should utilize your
MySet class to solve this problem. If no solution exists, print, “No solution exists” to the console. If a solution exists,
print the contents of each set, and the sum.
Example 1:
Enter a set of numbers: 1 2 3 4
<1,4> = <2,3> = 5
Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <vector>

using namespace std;

class MySet{

   vector<int> elements;
public:
	
    MySet();
	MySet(vector<int> elements);
	void addElement(int value);
	int removeElement(int index);
	int sum();
	int size();
};


MySet::MySet (){
    vector <int> elements;
}
void MySet::addElement(int value){
	elements.push_back(value);
}
int MySet::removeElement(int index){
elements.erase(elements.begin()+index);
return index;
}


int MySet::size(){
	return elements.size();

}
int MySet::sum(){
int i, sum = 0;
for (i=0; i< elements.size(); i++){
  sum += elements[i];
}
 return sum;
}

int main(int argc, char *argv[]){
	int value;
	MySet set;
	cout << "Enter your numbers,(enter -1 to end)" << endl;
while(cin){
  cin>> value;
  if(value==-1)
    break;
  set.addElement(value);
}
 
    cout<<"size: "<<int(set.size())<<endl;
	cout<<"total sum: "<<set.sum()<<endl;
	cout<<"deleted index: "<<set.removeElement(0)<<endl;
	cout<<"size: "<<int(set.size())<<endl;
	cout<<"total sum: "<<set.sum()<<endl;
	system("PAUSE");
	
}
Last edited on
Your MySet should probably have a bit more interface.

As to the problem.
If setC == setA + setB
and setA.sum() == setB.sum() == sumS
then 2 * sumS == setC.sum()

Therefore,
If setC.sum() is odd, then there is no solution
If any element is larger than setC.sum() / 2 then there is no solution

You could try to move the largest element to the other set (setB) first.
Then you still have to find elements from setA that sum up to sumS - setB.sum()
Topic archived. No new replies allowed.