Введение
Проблема решения в информатике. Проблема суммы подмножеств (SSP) — это проблема решения в информатике. В наиболее общей формулировке задано множество целых чисел и целевая сумма, и требуется определить, существует ли подмножество этих чисел, сумма элементов которого равна целевой сумме. Проблема известна как NP-трудная. Более того, некоторые её ограниченные варианты также являются NP-полными, например: Её также можно доказать сведением к задаче трёхмерного соответствия (3DM):
The subset sum problem (SSP) is a decision problem in computer science. In its most general formulation, there is a multiset of integers and a target sum , and the question is to decide whether any subset of the integers sum to precisely The problem is known to be NP hard. Moreover, some restricted variants of it are NP complete too, for example: It can also be proved by reduction from 3 dimensional matching (3DM):
We are given an instance of 3DM, where the vertex sets are W, X, Y. Each set has n vertices. There are m edges, where each edge contains exactly one vertex from each of W, X, Y. Denote L := ceiling(log2(m+1)), so that L is larger than the number of bits required to represent the number of edges. We construct an instance of SSP with m positive integers. The integers are described by their binary representation. Each input integer can be represented by 3nL bits, divided into 3n zones of L bits. Each zone corresponds to a vertex. For each edge (w,x,y) in the 3DM instance, there is an integer in the SSP instance, in which exactly three bits are "1": the least significant bits in the zones of the vertices w, x, and y. For example, if n=10 and L=3, and W=(0, ,9), X=(10, ,19), Y=(20, ,29), then the edge (0, 10, 20) is represented by the number (20+230+260). The target sum T in the SSP instance is set to an integer with "1" in the least significant bit of every zone, that is, (20+21+ +23n 1). If the 3DM instance has a perfect matching, then summing the corresponding integers in the SSP instance yields exactly T.
Conversely, if the SSP instance has a subset with sum exactly T, then, since the zones are sufficiently large so that there are no "carries" from one zone to the next, the sum must correspond to a perfect matching in the 3DM instance. The following variants are also known to be NP hard:
The input integers can be both positive and negative, and the target sum T = 0. This can be proved by reduction from the variant with positive integers. Denote that variant by SubsetSumPositive and the current variant by SubsetSumZero. Given an instance (S, T) of SubsetSumPositive, construct an instance of SubsetSumZero by adding a single element with value −T. Given a solution to the SubsetSumPositive instance, adding the −T yields a solution to the SubsetSumZero instance. Conversely, given a solution to the SubsetSumZero instance, it must contain the −T (since all integers in S are positive), so to get a sum of zero, it must also contain a subset of S with a sum of +T, which is a solution of the SubsetSumPositive instance. The input integers are positive, and T = sum(S)/2. This can also be proved by reduction from the general variant; see partition problem. The analogous counting problem #SSP, which asks to enumerate the number of subsets summing to the target, is #P complete.
Нам дан экземпляр 3DM, где множества вершин — W, X, Y. Каждое множество содержит n вершин. Существует m рёбер, каждое из которых соединяет ровно одну вершину из каждого из множеств W, X, Y. Обозначим L := ceiling(log2(m+1)), так что L больше, чем количество бит, необходимое для представления числа рёбер. Мы строим экземпляр SSP, состоящий из m положительных целых чисел. Целые числа представлены в двоичной форме. Каждое входное целое число может быть представлено 3nL битами, разделёнными на 3n зон по L битов. Каждая зона соответствует вершине. Для каждого ребра (w, x, y) в экземпляре 3DM существует целое число в экземпляре SSP, в котором ровно три бита установлены в "1": младшие биты в зонах, соответствующих вершинам w, x и y. Например, если n=10 и L=3, и W=(0, ..., 9), X=(10, ..., 19), Y=(20, ..., 29), то ребро (0, 10, 20) представлено числом (20 + 230 + 260). Целевая сумма T в экземпляре SSP устанавливается равной числу, в котором младший бит каждой зоны равен "1", то есть (20 + 21 + ... + 23n-1). Если экземпляр 3DM имеет совершенное соответствие, то суммирование соответствующих целых чисел в экземпляре SSP даёт ровно T.
The subset sum problem (SSP) is a decision problem in computer science. In its most general formulation, there is a multiset of integers and a target sum , and the question is to decide whether any subset of the integers sum to precisely The problem is known to be NP hard. Moreover, some restricted variants of it are NP complete too, for example: It can also be proved by reduction from 3 dimensional matching (3DM):
We are given an instance of 3DM, where the vertex sets are W, X, Y. Each set has n vertices. There are m edges, where each edge contains exactly one vertex from each of W, X, Y. Denote L := ceiling(log2(m+1)), so that L is larger than the number of bits required to represent the number of edges. We construct an instance of SSP with m positive integers. The integers are described by their binary representation. Each input integer can be represented by 3nL bits, divided into 3n zones of L bits. Each zone corresponds to a vertex. For each edge (w,x,y) in the 3DM instance, there is an integer in the SSP instance, in which exactly three bits are "1": the least significant bits in the zones of the vertices w, x, and y. For example, if n=10 and L=3, and W=(0, ,9), X=(10, ,19), Y=(20, ,29), then the edge (0, 10, 20) is represented by the number (20+230+260). The target sum T in the SSP instance is set to an integer with "1" in the least significant bit of every zone, that is, (20+21+ +23n 1). If the 3DM instance has a perfect matching, then summing the corresponding integers in the SSP instance yields exactly T.
Conversely, if the SSP instance has a subset with sum exactly T, then, since the zones are sufficiently large so that there are no "carries" from one zone to the next, the sum must correspond to a perfect matching in the 3DM instance. The following variants are also known to be NP hard:
The input integers can be both positive and negative, and the target sum T = 0. This can be proved by reduction from the variant with positive integers. Denote that variant by SubsetSumPositive and the current variant by SubsetSumZero. Given an instance (S, T) of SubsetSumPositive, construct an instance of SubsetSumZero by adding a single element with value −T. Given a solution to the SubsetSumPositive instance, adding the −T yields a solution to the SubsetSumZero instance. Conversely, given a solution to the SubsetSumZero instance, it must contain the −T (since all integers in S are positive), so to get a sum of zero, it must also contain a subset of S with a sum of +T, which is a solution of the SubsetSumPositive instance. The input integers are positive, and T = sum(S)/2. This can also be proved by reduction from the general variant; see partition problem. The analogous counting problem #SSP, which asks to enumerate the number of subsets summing to the target, is #P complete.
Обратно, если экземпляр SSP имеет подмножество с суммой, равной T, то, поскольку зоны достаточно велики, чтобы не было переносов из одной зоны в другую, эта сумма соответствует совершенному соответствию в экземпляре 3DM. Следующие варианты также известны как NP-трудные:
The subset sum problem (SSP) is a decision problem in computer science. In its most general formulation, there is a multiset of integers and a target sum , and the question is to decide whether any subset of the integers sum to precisely The problem is known to be NP hard. Moreover, some restricted variants of it are NP complete too, for example: It can also be proved by reduction from 3 dimensional matching (3DM):
We are given an instance of 3DM, where the vertex sets are W, X, Y. Each set has n vertices. There are m edges, where each edge contains exactly one vertex from each of W, X, Y. Denote L := ceiling(log2(m+1)), so that L is larger than the number of bits required to represent the number of edges. We construct an instance of SSP with m positive integers. The integers are described by their binary representation. Each input integer can be represented by 3nL bits, divided into 3n zones of L bits. Each zone corresponds to a vertex. For each edge (w,x,y) in the 3DM instance, there is an integer in the SSP instance, in which exactly three bits are "1": the least significant bits in the zones of the vertices w, x, and y. For example, if n=10 and L=3, and W=(0, ,9), X=(10, ,19), Y=(20, ,29), then the edge (0, 10, 20) is represented by the number (20+230+260). The target sum T in the SSP instance is set to an integer with "1" in the least significant bit of every zone, that is, (20+21+ +23n 1). If the 3DM instance has a perfect matching, then summing the corresponding integers in the SSP instance yields exactly T.
Conversely, if the SSP instance has a subset with sum exactly T, then, since the zones are sufficiently large so that there are no "carries" from one zone to the next, the sum must correspond to a perfect matching in the 3DM instance. The following variants are also known to be NP hard:
The input integers can be both positive and negative, and the target sum T = 0. This can be proved by reduction from the variant with positive integers. Denote that variant by SubsetSumPositive and the current variant by SubsetSumZero. Given an instance (S, T) of SubsetSumPositive, construct an instance of SubsetSumZero by adding a single element with value −T. Given a solution to the SubsetSumPositive instance, adding the −T yields a solution to the SubsetSumZero instance. Conversely, given a solution to the SubsetSumZero instance, it must contain the −T (since all integers in S are positive), so to get a sum of zero, it must also contain a subset of S with a sum of +T, which is a solution of the SubsetSumPositive instance. The input integers are positive, and T = sum(S)/2. This can also be proved by reduction from the general variant; see partition problem. The analogous counting problem #SSP, which asks to enumerate the number of subsets summing to the target, is #P complete.
Входные целые числа могут быть как положительными, так и отрицательными, а целевая сумма T = 0. Это можно доказать сведением к варианту с положительными целыми числами. Обозначим этот вариант как SubsetSumPositive, а текущий вариант — как SubsetSumZero. Для заданного экземпляра (S, T) задачи SubsetSumPositive построим экземпляр SubsetSumZero, добавив один элемент со значением −T. Если дано решение для экземпляра SubsetSumPositive, то добавление −T даёт решение для экземпляра SubsetSumZero. И наоборот, если дано решение для экземпляра SubsetSumZero, оно должно содержать −T (поскольку все целые числа в S положительные), следовательно, для получения суммы, равной нулю, оно также должно содержать подмножество S с суммой +T, которое является решением экземпляра SubsetSumPositive. Входные целые числа положительные, и T = sum(S)/2. Это также можно доказать сведением к общему варианту; см. задачу о разбиении. Аналогичная задача подсчёта #SSP, которая требует перечислить количество подмножеств, дающих целевую сумму, является #P-полной.
The subset sum problem (SSP) is a decision problem in computer science. In its most general formulation, there is a multiset of integers and a target sum , and the question is to decide whether any subset of the integers sum to precisely The problem is known to be NP hard. Moreover, some restricted variants of it are NP complete too, for example: It can also be proved by reduction from 3 dimensional matching (3DM):
We are given an instance of 3DM, where the vertex sets are W, X, Y. Each set has n vertices. There are m edges, where each edge contains exactly one vertex from each of W, X, Y. Denote L := ceiling(log2(m+1)), so that L is larger than the number of bits required to represent the number of edges. We construct an instance of SSP with m positive integers. The integers are described by their binary representation. Each input integer can be represented by 3nL bits, divided into 3n zones of L bits. Each zone corresponds to a vertex. For each edge (w,x,y) in the 3DM instance, there is an integer in the SSP instance, in which exactly three bits are "1": the least significant bits in the zones of the vertices w, x, and y. For example, if n=10 and L=3, and W=(0, ,9), X=(10, ,19), Y=(20, ,29), then the edge (0, 10, 20) is represented by the number (20+230+260). The target sum T in the SSP instance is set to an integer with "1" in the least significant bit of every zone, that is, (20+21+ +23n 1). If the 3DM instance has a perfect matching, then summing the corresponding integers in the SSP instance yields exactly T.
Conversely, if the SSP instance has a subset with sum exactly T, then, since the zones are sufficiently large so that there are no "carries" from one zone to the next, the sum must correspond to a perfect matching in the 3DM instance. The following variants are also known to be NP hard:
The input integers can be both positive and negative, and the target sum T = 0. This can be proved by reduction from the variant with positive integers. Denote that variant by SubsetSumPositive and the current variant by SubsetSumZero. Given an instance (S, T) of SubsetSumPositive, construct an instance of SubsetSumZero by adding a single element with value −T. Given a solution to the SubsetSumPositive instance, adding the −T yields a solution to the SubsetSumZero instance. Conversely, given a solution to the SubsetSumZero instance, it must contain the −T (since all integers in S are positive), so to get a sum of zero, it must also contain a subset of S with a sum of +T, which is a solution of the SubsetSumPositive instance. The input integers are positive, and T = sum(S)/2. This can also be proved by reduction from the general variant; see partition problem. The analogous counting problem #SSP, which asks to enumerate the number of subsets summing to the target, is #P complete.
Экспоненциальные алгоритмы времени
Существует несколько способов решения задачи SSP за время, экспоненциальное относительно n.
Включение/исключение
Самый наивный алгоритм — перебрать все подмножества из n чисел и для каждого из них проверить, равна ли сумма подмножества целевому числу. Время выполнения составляет O(2^n), так как существует 2^n подмножеств, и для проверки каждого подмножества требуется суммировать не более n элементов. Алгоритм можно реализовать с помощью поиска в глубину в двоичном дереве: каждый уровень дерева соответствует входному числу; левая ветвь соответствует исключению числа из множества, а правая ветвь — включению числа (отсюда и название «включение-исключение»). Требуемая память составляет O(n). Время выполнения можно улучшить с помощью нескольких эвристик: был опубликован более быстрый алгоритм экспоненциального времени, работающий за время O(c^n) (где c < 2), но требующий значительно больше памяти. Этот алгоритм произвольно разделяет n элементов на два множества по n/2 элементов в каждом. Для каждого из этих двух множеств он хранит список сумм всех возможных подмножеств его элементов. Каждый из этих двух списков затем сортируется. Однако, даже при использовании самого быстрого алгоритма сравнения, например, сортировки слиянием, этот шаг займет время O(n log n). Но, имея отсортированный список сумм для n элементов, список можно расширить до двух отсортированных списков при добавлении (n+1)-го элемента, и эти два отсортированных списка можно объединить за время O(n). Таким образом, каждый список можно сгенерировать в отсортированном виде за время O(n log n). Имея два отсортированных списка, алгоритм может проверить, есть ли элемент в первом массиве и элемент во втором массиве, сумма которых равна T, за время O(n). Для этого алгоритм проходит по первому массиву в порядке убывания (начиная с наибольшего элемента) и по второму массиву в порядке возрастания (начиная с наименьшего элемента). Если сумма текущего элемента в первом массиве и текущего элемента во втором массиве больше T, алгоритм переходит к следующему элементу в первом массиве. Если она меньше T, алгоритм переходит к следующему элементу во втором массиве. Если найдены два элемента, сумма которых равна T, алгоритм останавливается. (Подзадача поиска суммы двух элементов известна как задача о двух суммах.)
Шропель и Шамир
В 1981 году Шроеппель и Шамир представили алгоритм, основанный на алгоритме Хоровица и Санхи, требующий схожего времени выполнения, но значительно меньше памяти. Вместо предварительного генерирования и хранения всех подмножеств из n/2 элементов, они разделяют элементы на 4 множества по n/4 элементов каждое и динамически генерируют подмножества пар элементов по n/2, используя минимальную кучу. Это обеспечивает указанную временную и пространственную сложность, поскольку это можно выполнить за время и память, используя 4 списка длиной k.
Из-за требований к памяти алгоритм HS практичен для примерно 50 целых чисел, а алгоритм SS – для до 100 целых чисел. Был представлен вероятностный алгоритм, работающий быстрее всех предыдущих за время, используя память. Он решает только задачу определения существования решения, не может доказать отсутствие решения для заданной суммы и не возвращает подмножество с суммой, наиболее близкой к T.
Методы Хоугрейва-Грэма и Жоукса впоследствии были расширены, что позволило снизить временную сложность до .
Алгоритмы приближения в полиномиальном времени
Предположим, все входные данные положительны. Алгоритм приближения для задачи SSP стремится найти подмножество S с суммой не более T и не менее чем в r раз превышающей оптимальную сумму, где r – число из интервала (0, 1), называемое коэффициентом приближения.