Last active
November 13, 2019 17:44
-
-
Save tomilov/c626e5fc4c71c157c31bd0e984590756 to your computer and use it in GitHub Desktop.
dynamic dynamic programming for subset sum problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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