Skip to content

Instantly share code, notes, and snippets.

@tomilov
Last active November 13, 2019 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomilov/c626e5fc4c71c157c31bd0e984590756 to your computer and use it in GitHub Desktop.
Save tomilov/c626e5fc4c71c157c31bd0e984590756 to your computer and use it in GitHub Desktop.
dynamic dynamic programming for subset sum problem
#include <iostream>
#include <algorithm>
#include <cassert>
struct pair
{
int term;
int sum;
pair operator + (int x)
{
return {x, sum + x};
}
bool operator < (const pair & p) const
{
return sum < p.sum;
}
explicit operator bool () const
{
return term != 0;
}
bool operator == (const pair & p) const
{
return sum == p.sum;
}
};
pair ddp[2][1000];
auto src = ddp[0];
auto dst = ddp[1];
inline
auto add(int x)
{
assert(x != 0);
auto s = src;
auto cur = s;
auto d = dst;
do {
auto next = *s + x;
while (next < *cur) {
*d++ = *cur++;
}
#if 0
if (*cur == next) {
++cur;
}
*d++ = std::move(next);
#else
if (*cur == next) {
*d++ = *cur++;
} else {
*d++ = std::move(next);
}
#endif
} while (*s++);
while ((*d++ = *cur++));
std::swap(src, dst);
return (d - src);
}
int main()
{
int v[] = {1, 2, 4, 8, 16, 32, 64};
src[0] = {};
for (int x : v) {
add(x);
}
do {
std::cout << src->sum << ' ';
} while (*src++);
std::cout << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment