Localizando partições sem soma


17

Sumário executivo

Dada entrada k, encontrar uma partição de inteiros 1para na ksubconjuntos livre de soma para o maior npossível dentro de 10 minutos.

Contexto: números de Schur

Um conjunto Aé livre de soma se sua soma automática A + A = { x + y | x, y in A}não tiver elementos em comum com ele.

Para todo número inteiro positivo, kexiste um número inteiro maior, de S(k)modo que o conjunto {1, 2, ..., S(k)}pode ser particionado em ksubconjuntos sem soma. Esse número é chamado de k- ésimo número de Schur (OEIS A045652 ).

Por exemplo S(2) = 4,. Podemos particionar {1, 2, 3, 4}como {1, 4}, {2, 3}, e essa é a partição exclusiva em dois subconjuntos sem soma, mas agora não podemos adicionar um 5a nenhuma das partes.

Desafio

Escreva um programa determinístico que faça o seguinte:

  • Tome um número inteiro positivo kcomo entrada
  • Escreva o timestamp atual do Unix no stdout
  • Saídas uma sequência de partições de 1a nem ksubconjuntos livre de soma para o aumento n, após cada sequência com o timestamp Unix.

O vencedor será o programa que imprimirá uma partição para a maior ndentro de 10 minutos no meu computador quando receber uma entrada 5. Os laços serão quebrados no momento mais rápido para encontrar uma partição para a maior nmédia, em três execuções: é por isso que a saída deve incluir registros de data e hora.

Detalhes importantes:

  • Eu tenho o Ubuntu Precise, portanto, se seu idioma não for suportado, não poderei pontuá-lo.
  • Eu tenho uma CPU Intel Core2 Quad, portanto, se você quiser usar multithreading, não faz sentido usar mais de 4 threads.
  • Se você quiser que eu use quaisquer sinalizadores ou implementações específicas do compilador, documente isso claramente em sua resposta.
  • Você não deve especializar seu código para manipular a entrada 5.
  • Você não é obrigado a produzir todas as melhorias encontradas. Por exemplo, para a entrada 2você poderia saída apenas a partição para n = 4. No entanto, se você não produzir nada nos primeiros 10 minutos, pontuarei isso como n = 0.

Respostas:


8

Python 3, classifique pelo maior número, n = 92 121

Agradecemos a Martin Büttner por uma sugestão que inesperadamente melhorou o máximo natingido.

Última saída:

[2, 3, 11, 12, 29, 30, 38, 39, 83, 84, 92, 93, 110, 111, 119, 120]
[1, 4, 10, 13, 28, 31, 37, 40, 82, 85, 91, 94, 109, 112, 118, 121]
[5, 6, 7, 8, 9, 32, 33, 34, 35, 36, 86, 87, 88, 89, 90, 113, 114, 115, 116, 117]
[14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81]

O algoritmo é o mesmo da minha resposta anterior, citada abaixo:

Existem k posições que possuem os números até agora e os números que não podem mais ser inseridos. A cada profundidade da iteração (é basicamente uma pesquisa de profundidade), a ordem das posições é embaralhada e o próximo número (nextN) é (sequencialmente) colocado nas caixas que podem levá-la e, em seguida, é um passo mais profundo. Se não houver, ele retornará, fazendo backup de uma etapa.

... com uma exceção: a ordem do compartimento não é embaralhada. Em vez disso, é classificada de tal maneira que os compartimentos com o maior número são os primeiros. Isso chegou n = 121em 8 segundos!

Código:

from copy import deepcopy
from random import shuffle, seed
from time import clock, time
global maxN
maxN = 0
clock()

def search(k,nextN=1,sets=None):
    global maxN
    if clock() > 600: return

    if nextN == 1: #first iteration
        sets = []
        for i in range(k):
            sets.append([[],[]])

    sets.sort(key=lambda x:max(x[0]or[0]), reverse=True)
    for i in range(k):
        if clock() > 600: return
        if nextN not in sets[i][1]:
            sets2 = deepcopy(sets)
            sets2[i][0].append(nextN)
            sets2[i][1].extend([nextN+j for j in sets2[i][0]])
            nextN2 = nextN + 1

            if nextN > maxN:
                maxN = nextN
                print("New maximum!",maxN)
                for s in sets2: print(s[0])
                print(time())
                print()

            search(k, nextN2, sets2)

search(5)

Nota: classificando pelo maior número de números permitidos dentro do intervalo de números não permitidos n=59, e classificando pelo maior número de números permitidos menor que o que nextNfornece n=64. A classificação pelo comprimento da lista de números não permitidos (que pode ter repetições) leva muito rapidamente a um n=30padrão elegante .
El'endia Starman 9/11/2015

O formato do horário de saída não está correto (deve ser segundos desde a época, mas estou vendo Tue Nov 10 00:44:25 2015), mas vi n=92em menos de 2 segundos.
Peter Taylor

Ah, achei que o formato da hora não era tão importante quanto mostrar exatamente quanto tempo levou. Eu vou descobrir e mudar isso embora. Edição: D'oh. Peguei ctimemais timeporque a saída era mais bonita quando timefoi exatamente o que eu deveria ter escolhido.
El'endia Starman 10/11/2015

Você sabe, você também pode apenas classificar pelo maior número na lixeira, porque o maior número não permitido será sempre o dobro disso.
Martin Ender

@ MartinBüttner: ...... eu ... uh ... eu não tenho idéia de como ou por quê, mas isso acontece n=121. oO
El'endia Starman 10/11/2015

7

Python 3, 121, <0,001s

Graças à heurística aprimorada, Martin Buttner significa que nem precisamos de aleatoriedade.

Resultado:

1447152500.9339304
[1, 4, 10, 13, 28, 31, 37, 40, 82, 85, 91, 94, 109, 112, 118, 121]
[2, 3, 11, 12, 29, 30, 38, 39, 83, 84, 92, 93, 110, 111, 119, 120]
[5, 6, 7, 8, 9, 32, 33, 34, 35, 36, 86, 87, 88, 89, 90, 113, 114, 115, 116, 117]
[14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81]
1447152500.934646 121

Código:

from copy import deepcopy
from random import seed, randrange
from time import clock, time
from cProfile import run

n = 5

seed(0)

def heuristic(bucket):
    return len(bucket[0]) and bucket[0][-1]

def search():
    best = 0
    next_add = 1
    old_add = 0
    lists = [[[],set()] for _ in range(n)]
    print(time())
    while clock() < 600 and next_add != old_add:
        old_add = next_add
        lists.sort(key=heuristic, reverse=True)
        for i in range(n):
            if next_add not in lists[i][1]:
                lists[i][0].append(next_add)
                lists[i][1].update([next_add + old for old in lists[i][0]])
                if next_add > best:
                    best = next_add
                next_add += 1
                break

    for l in lists:
        print(l[0])
    print(time(), next_add-1, end='\n\n')

search()

Python 3, 112

Classificar pela soma dos 2 primeiros elementos + inclinação

[40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
[7, 8, 9, 10, 11, 12, 13, 27, 28, 29, 30, 31, 32, 33, 80, 81, 82, 83, 84, 85, 86, 100, 101, 102, 103, 104, 105, 106]
[3, 4, 14, 19, 21, 26, 36, 37, 87, 92, 94, 99, 109, 110]
[2, 5, 16, 17, 20, 23, 24, 35, 38, 89, 90, 96, 97, 108, 111]
[1, 6, 15, 18, 22, 25, 34, 39, 88, 91, 93, 95, 98, 107, 112]
1447137688.032085 138.917074 112

Copiei a estrutura de dados de El'endia Starman, que consiste em uma lista de pares, em que o primeiro elemento do par são os elementos desse balde e o segundo é a soma desse balde.

Começo com a mesma abordagem "rastrear quais somas estão disponíveis". Minha heurística de classificação é simplesmente a soma dos dois menores elementos de uma determinada lista. Também adiciono uma pequena inclinação aleatória para tentar diferentes possibilidades.

Cada iteração simplesmente coloca o novo número na primeira posição disponível, semelhante à ganância aleatória. Quando isso falha, simplesmente reinicia.

from copy import deepcopy
from random import seed, randrange
from time import clock, time

n = 5

seed(0)

def skew():
    return randrange(9)

best = 0
next_add = old_add = 1
while clock() < 600:
    if next_add == old_add:
        lists = [[[],[]] for _ in range(n)]
        next_add = old_add = 1
    old_add = next_add
    lists.sort(key=lambda x:sum(x[0][:2]) + skew(), reverse=True)
    for i in range(n):
        if next_add not in lists[i][1]:
            lists[i][0].append(next_add)
            lists[i][1].extend([next_add + old for old in lists[i][0]])
            if next_add > best:
                best = next_add
                for l in lists:
                    print(l[0])
                print(time(), clock(), next_add, end='\n\n')
            next_add += 1
            break

Uau, isso parece extremamente semelhante ao meu código. : P;) (eu não me importo.)
El'endia Starman 10/11/2015

@ El'endiaStarman Crédito adicionado. É uma boa base.
Isaacg

7

Java 8, n = 142 144

Última saída:

@ 0m 31s 0ms
n: 144
[9, 12, 17, 20, 22, 23, 28, 30, 33, 38, 41, 59, 62, 65, 67, 70, 72, 73, 75, 78, 80, 83, 86, 91, 107, 115, 117, 122, 123, 125, 128, 133, 136]
[3, 8, 15, 24, 25, 26, 31, 35, 45, 47, 54, 58, 64, 68, 81, 87, 98, 100, 110, 114, 119, 120, 121, 130, 137, 142]
[5, 13, 16, 19, 27, 36, 39, 42, 48, 50, 51, 94, 95, 97, 103, 106, 109, 112, 118, 126, 129, 132, 138, 140, 141]
[2, 6, 11, 14, 34, 37, 44, 53, 56, 61, 69, 76, 79, 84, 89, 92, 101, 104, 108, 111, 124, 131, 134, 139, 143, 144]
[1, 4, 7, 10, 18, 21, 29, 32, 40, 43, 46, 49, 52, 55, 57, 60, 63, 66, 71, 74, 77, 82, 85, 88, 90, 93, 96, 99, 102, 105, 113, 116, 127, 135]

Executa uma pesquisa aleatória distribuída em 4 threads. Quando não consegue encontrar uma partição para cabern , tenta liberar espaço para numa partição de cada vez, despejando o máximo possível nas outras partições.

edit: ajustou o algoritmo para liberar espaço para n , também adicionou a capacidade de voltar para uma opção anterior e escolher novamente.

nota: a saída não é estritamente determinística porque há vários threads envolvidos e eles podem acabar atualizando os melhores n encontrados até agora em ordem confusa; a pontuação final de 144 é determinística e é alcançada rapidamente: 30 segundos no meu computador.

O código é:

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class SumFree {

    private static int best;

    public static void main(String[] args) {
        int k = 5; // Integer.valueOf(args[0]);
        int numThreadsPeterTaylorCanHandle = 4;

        long start = System.currentTimeMillis();
        long end = start + TimeUnit.MINUTES.toMillis(10);

        System.out.println(start);

        Random rand = new Random("Lucky".hashCode());
        for (int i = 0; i < numThreadsPeterTaylorCanHandle; i++) {
            new Thread(() -> search(k, new Random(rand.nextLong()), start, end)).start();
        }
    }

    private static void search(int k, Random rand, long start, long end) {
        long now = System.currentTimeMillis();
        int localBest = 0;

        do {
            // create k empty partitions
            List<Partition> partitions = new ArrayList<>();
            for (int i = 0; i < k; i++) {
                partitions.add(new Partition());
            }

            Deque<Choice> pastChoices = new ArrayDeque<>();
            int bestNThisRun = 0;

            // try to fill up the partitions as much as we can
            for (int n = 1;; n++) {
                // list of partitions that can fit n
                List<Partition> partitionsForN = new ArrayList<>(k);
                for (Partition partition : partitions) {
                    if (!partition.sums.contains(n)) {
                        partitionsForN.add(partition);
                    }
                }

                // if we can't fit n anywhere then try to free up some space
                // by rearranging partitions
                Set<Set<Set<Integer>>> rearrangeAttempts = new HashSet<>();
                rearrange: while (partitionsForN.size() == 0 && rearrangeAttempts
                        .add(partitions.stream().map(Partition::getElements).collect(Collectors.toSet()))) {

                    Collections.shuffle(partitions, rand);
                    for (int candidateIndex = 0; candidateIndex < k; candidateIndex++) {
                        // partition we will try to free up
                        Partition candidate = partitions.get(candidateIndex);
                        // try to dump stuff that adds up to n into the other
                        // partitions
                        List<Integer> badElements = new ArrayList<>(candidate.elements.size());
                        for (int candidateElement : candidate.elements) {
                            if (candidate.elements.contains(n - candidateElement)) {
                                badElements.add(candidateElement);
                            }
                        }
                        for (int i = 0; i < k && !badElements.isEmpty(); i++) {
                            if (i == candidateIndex) {
                                continue;
                            }

                            Partition other = partitions.get(i);

                            for (int j = 0; j < badElements.size(); j++) {
                                int candidateElement = badElements.get(j);
                                if (!other.sums.contains(candidateElement)
                                        && !other.elements.contains(candidateElement + candidateElement)) {
                                    boolean canFit = true;
                                    for (int otherElement : other.elements) {
                                        if (other.elements.contains(candidateElement + otherElement)) {
                                            canFit = false;
                                            break;
                                        }
                                    }

                                    if (canFit) {
                                        other.elements.add(candidateElement);
                                        for (int otherElement : other.elements) {
                                            other.sums.add(candidateElement + otherElement);
                                        }
                                        candidate.elements.remove((Integer) candidateElement);
                                        badElements.remove(j--);
                                    }
                                }
                            }
                        }

                        // recompute the sums
                        candidate.sums.clear();
                        List<Integer> elementList = new ArrayList<>(candidate.elements);
                        int elementListSize = elementList.size();
                        for (int i = 0; i < elementListSize; i++) {
                            int ithElement = elementList.get(i);
                            for (int j = i; j < elementListSize; j++) {
                                int jthElement = elementList.get(j);
                                candidate.sums.add(ithElement + jthElement);
                            }
                        }

                        // if candidate can now fit n then we can go on
                        if (!candidate.sums.contains(n)) {
                            partitionsForN.add(candidate);
                            break rearrange;
                        }
                    }
                }

                // if we still can't fit in n, then go back in time to our last
                // choice (if it's saved) and this time choose differently
                if (partitionsForN.size() == 0 && !pastChoices.isEmpty() && bestNThisRun > localBest - localBest / 3) {
                    Choice lastChoice = pastChoices.peek();
                    partitions = new ArrayList<>(lastChoice.partitions.size());
                    for (Partition partition : lastChoice.partitions) {
                        partitions.add(new Partition(partition));
                    }
                    n = lastChoice.n;
                    Partition partition = lastChoice.unchosenPartitions
                            .get(rand.nextInt(lastChoice.unchosenPartitions.size()));
                    lastChoice.unchosenPartitions.remove(partition);
                    partition = partitions.get(lastChoice.partitions.indexOf(partition));
                    partition.elements.add(n);
                    for (int element : partition.elements) {
                        partition.sums.add(element + n);
                    }
                    if (lastChoice.unchosenPartitions.size() == 0) {
                        pastChoices.pop();
                    }
                    continue;
                }

                if (partitionsForN.size() > 0) {
                    // if we can fit in n somewhere,
                    // pick that somewhere randomly
                    Partition chosenPartition = partitionsForN.get(rand.nextInt(partitionsForN.size()));
                    // if we're making a choice then record it so that we may
                    // return to it later if we get stuck
                    if (partitionsForN.size() > 1) {
                        Choice choice = new Choice();
                        choice.n = n;
                        for (Partition partition : partitions) {
                            choice.partitions.add(new Partition(partition));
                        }
                        for (Partition partition : partitionsForN) {
                            if (partition != chosenPartition) {
                                choice.unchosenPartitions.add(choice.partitions.get(partitions.indexOf(partition)));
                            }
                        }
                        pastChoices.push(choice);

                        // only keep 3 choices around
                        if (pastChoices.size() > 3) {
                            pastChoices.removeLast();
                        }
                    }

                    chosenPartition.elements.add(n);
                    for (int element : chosenPartition.elements) {
                        chosenPartition.sums.add(element + n);
                    }
                    bestNThisRun = Math.max(bestNThisRun, n);
                }

                if (bestNThisRun > localBest) {
                    localBest = Math.max(localBest, bestNThisRun);

                    synchronized (SumFree.class) {
                        now = System.currentTimeMillis();

                        if (bestNThisRun > best) {
                            // sanity check
                            Set<Integer> allElements = new HashSet<>();
                            for (Partition partition : partitions) {
                                for (int e1 : partition.elements) {
                                    if (!allElements.add(e1)) {
                                        throw new RuntimeException("Oops!");
                                    }
                                    for (int e2 : partition.elements) {
                                        if (partition.elements.contains(e1 + e2)) {
                                            throw new RuntimeException("Oops!");
                                        }
                                    }
                                }
                            }
                            if (allElements.size() != bestNThisRun) {
                                throw new RuntimeException("Oops!" + allElements.size() + "!=" + bestNThisRun);
                            }

                            best = bestNThisRun;
                            System.out.printf("@ %dm %ds %dms\n", TimeUnit.MILLISECONDS.toMinutes(now - start),
                                    TimeUnit.MILLISECONDS.toSeconds(now - start) % 60, (now - start) % 1000);
                            System.out.printf("n: %d\n", bestNThisRun);
                            for (Partition partition : partitions) {
                                // print in sorted order since everyone else
                                // seems to to that
                                List<Integer> partitionElementsList = new ArrayList<>(partition.elements);
                                Collections.sort(partitionElementsList);
                                System.out.println(partitionElementsList);
                            }
                            System.out.printf("timestamp: %d\n", now);
                            System.out.println("------------------------------");
                        }
                    }
                }

                if (partitionsForN.size() == 0) {
                    break;
                }
            }
        } while (now < end);
    }

    // class representing a partition
    private static final class Partition {

        // the elements of this partition
        Set<Integer> elements = new HashSet<>();

        // the sums of the elements of this partition
        Set<Integer> sums = new HashSet<>();

        Partition() {
        }

        Partition(Partition toCopy) {
            elements.addAll(toCopy.elements);
            sums.addAll(toCopy.sums);
        }

        Set<Integer> getElements() {
            return elements;
        }
    }

    private static final class Choice {
        int n;
        List<Partition> partitions = new ArrayList<>();
        List<Partition> unchosenPartitions = new ArrayList<>();
    }
}

5

C, Ganancioso Aleatório, n = 91

Apenas para fornecer uma solução de linha de base, ele repete n, acompanhando os compartimentos e suas somas e adiciona na uma lixeira aleatória onde ainda não aparece como uma soma. Ele termina uma vez que naparece em todas as ksomas e se o resultado resultanten foi melhor do que qualquer tentativa anterior, imprime-o em STDOUT.

A entrada ké fornecida através de um argumento de linha de comando. O máximo possívelk é codificado para 10, porque eu estava com preguiça de adicionar alocação dinâmica de memória, mas isso poderia ser corrigido facilmente.

Acho que eu poderia procurar uma semente melhor agora, mas essa resposta provavelmente não é particularmente competitiva, então meh.

Aqui está a partição para n = 91:

1 5 12 18 22 29 32 35 46 48 56 59 62 69 72 76 79 82 86 89
2 3 10 11 16 17 25 30 43 44 51 52 57 64 71 83 84 90 91
6 8 13 15 24 31 33 38 40 42 49 54 61 63 65 77 81 88
9 14 19 21 27 34 37 45 60 67 70 73 75 78 80 85
4 7 20 23 26 28 36 39 41 47 50 53 55 58 66 68 74 87

E finalmente, aqui está o código:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define MAX_K 10
#define MAX_N 1024

int main(int argc, char **argv) {
    if (argc < 2)
    {
        printf("Pass in k as a command-line argument");
        return 1;
    }

    printf("%u\n", (unsigned)time(NULL)); 

    int k = atoi(argv[1]);

    int sizes[MAX_K];
    int bins[MAX_K][MAX_N];
    int sums[MAX_K][2*MAX_N];
    int selection[MAX_K];
    int available_bins;

    int best = 0;

    srand(1447101176);

    while (1)
    {
        int i,j;
        for (i = 0; i < k; ++i)
            sizes[i] = 0;
        for (i = 0; i < k*MAX_N; ++i)
            bins[0][i] = 0;
        for (i = 0; i < k*MAX_N*2; ++i)
            sums[0][i] = 0;
        int n = 1;
        while (1)
        {
            available_bins = 0;
            for (i = 0; i < k; ++i)
                if (!sums[i][n])
                {
                    selection[available_bins] = i;
                    ++available_bins;
                }

            if (!available_bins) break;

            int bin = selection[rand() % available_bins];

            bins[bin][sizes[bin]] = n;
            ++sizes[bin];
            for (i = 0; i < sizes[bin]; ++i)
                sums[bin][bins[bin][i] + n] = 1;

            ++n;
        }

        if (n > best)
        {
            best = n;
            for (i = 0; i < k; ++i)
            {
                for (j = 0; j < sizes[i]; ++j)
                    printf("%d ", bins[i][j]);
                printf("\n");
            }
            printf("%u\n", (unsigned)time(NULL));
        }
    }

    return 0;
}

Confirmado n=91, encontrado em 138 segundos. Se necessário para desempate, eu voltarei a trabalhar para evitar grandes erros devido à carga da CPU diferente.
22468 Peter

3

C ++, 135

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <set>
#include <vector>
#include <algorithm>


using namespace std;

vector<vector<int> > subset;
vector<int> len, tmp;
set<int> sums;

bool is_sum_free_with(int elem, int subnr) {
    sums.clear();
    sums.insert(elem+elem);
    for(int i=0; i<len[subnr]; ++i) {
        sums.insert(subset[subnr][i]+elem);
        for(int j=i; j<len[subnr]; ++j) sums.insert(subset[subnr][i]+subset[subnr][j]);
    }
    if(sums.find(elem)!=sums.end()) return false;
    for(int i=0; i<len[subnr]; ++i) if(sums.find(subset[subnr][i])!=sums.end()) return false;
    return true;
}

int main()
{
    int k = 0; cin >> k;

    int start=time(0);
    cout << start << endl;

    int allmax=0, cnt=0;
    srand(0);

    do {
        len.clear();
        len.resize(k);
        subset.clear();
        subset.resize(k);
        for(int i=0; i<k; ++i) subset[i].resize((int)pow(3, k));

        int n=0, last=0, c, y, g, h, t, max=0;
        vector<int> p(k);

        do {
            ++n;
            c=-1;
            for(int i=0; i++<k; ) {
                y=(last+i)%k;
                if(is_sum_free_with(n, y)) p[++c]=y;
            }

            if(c<0) --n;

            t=n;

            while(c<0) {
                g=rand()%k;
                h=rand()%len[g];
                t=subset[g][h];
                for(int l=h; l<len[g]-1; ++l) subset[g][l]=subset[g][l+1];
                --len[g];
                for(int i=0; i++<k; ) {
                    y=(g+i)%k;
                    if(is_sum_free_with(t, y) && y!=g) p[++c]=y;
                }
                if(c<0) subset[g][len[g]++]=t;
            }

            c=p[rand()%(c+1)];
            subset[c][len[c]++]=t;

            last=c;

            if(n>max) {
                max=n;
                cnt=0;
                if(n>allmax) {
                    allmax=n;
                    for(int i=0; i<k; ++i) {
                        tmp.clear();
                        for(int j=0; j<len[i]; ++j) tmp.push_back(subset[i][j]);
                        sort(tmp.begin(), tmp.end());
                        for(int j=0; j<len[i]; ++j) cout << tmp[j] << " ";
                        cout << endl;
                    }
                    cout << time(0) << " " << time(0)-start << " " << allmax << endl;
                }

            }

        } while(++cnt<50*n && time(0)-start<600);

        cnt=0;

    } while(time(0)-start<600);

    return 0;
}

Anexa o próximo n a um subconjunto escolhido aleatoriamente. Se isso não for possível, ele remove números aleatórios de subconjuntos e os anexa a outros na esperança de que isso permita acrescentar n em algum lugar.

Eu prototipei isso no awk e, como parecia promissor, eu o traduzi para C ++ para acelerar. Usando umstd::set deve até acelerar mais.

Saída para n = 135 (após cerca de 230 segundos na minha máquina [antiga])

2 6 9 10 13 17 24 28 31 35 39 42 43 46 50 57 61 68 75 79 90 94 97 101 105 108 119 123 126 127 130 131 134 
38 41 45 48 51 52 55 56 58 59 62 64 65 66 67 69 70 71 72 74 78 80 81 84 85 87 88 91 95 98 
5 12 15 16 19 22 23 25 26 29 33 36 73 83 93 100 103 107 110 111 113 114 117 120 121 124 
1 4 11 14 21 27 34 37 40 47 53 60 76 86 89 96 99 102 109 112 115 122 125 132 135 
3 7 8 18 20 30 32 44 49 54 63 77 82 92 104 106 116 118 128 129 133 

Não verifiquei novamente a validade, mas deve estar tudo bem.


2

Python 3, ganancioso aleatório, n = 61

Última saída:

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

Utiliza efetivamente o mesmo algoritmo que Martin Büttner , mas eu o desenvolvi de forma independente.

Existem kbandejas que possuem os números até agora e os números que não podem mais ser inseridos. A cada profundidade da iteração (é basicamente uma pesquisa de profundidade), a ordem nextNdas posições é embaralhada e o próximo número ( ) é (sequencialmente) colocado nas caixas que podem levá-la e, em seguida, é um passo mais profundo. Se não houver, ele retornará, fazendo backup de uma etapa.

from copy import deepcopy
from random import shuffle, seed
from time import clock, time
global maxN
maxN = 0
clock()
seed(0)

def search(k,nextN=1,sets=None):
    global maxN
    if clock() > 600: return

    if nextN == 1: #first iteration
        sets = []
        for i in range(k):
            sets.append([[],[]])

    R = list(range(k))
    shuffle(R)
    for i in R:
        if clock() > 600: return
        if nextN not in sets[i][1]:
            sets2 = deepcopy(sets)
            sets2[i][0].append(nextN)
            sets2[i][1].extend([nextN+j for j in sets2[i][0]])
            nextN2 = nextN + 1

            if nextN > maxN:
                maxN = nextN
                print("New maximum!",maxN)
                for s in sets2: print(s[0])
                print(time())
                print()

            search(k, nextN2, sets2)

search(5)

2

Python, n = 31

import sys
k = int(sys.argv[1])

for i in range(k):
    print ([2**i * (2*j + 1) for j in range(2**(k - i - 1))])

Ok, então, obviamente, não é um vencedor, mas eu senti que pertencia aqui de qualquer maneira. Tomei a liberdade de não incluir registros de data e hora, pois termina instantaneamente e não é um candidato real.

Primeiro, observe que a soma de quaisquer dois números ímpares é par, para que possamos despejar todos os números ímpares no primeiro bloco. Então, como todos os números restantes são pares, podemos dividi-los por 2. Mais uma vez, podemos lançar todos os números ímpares resultantes no segundo bloco (depois de re-multiplicá-los por 2), divida os números restantes por 2 (ou seja, , por 4 no total), jogue os ímpares no terceiro bloco (depois de multiplicá-los por 4) e assim por diante ... Ou, para colocar as palavras que vocês entendem, colocamos todos os números cujo conjunto menos significativo bit é o primeiro bit no primeiro bloco, todos os números cujo bit de conjunto menos significativo é o segundo bit no segundo bloco e assim por diante ...

Para os blocos k , enfrentamos problemas quando atingimos n = 2 k , já que o bit conjunto menos significativo de n é
o ( k + 1) -ésimo bit, que não corresponde a nenhum bloco. Em outras palavras, este esquema funciona até
para n = 2 k - 1. Assim, enquanto que para k = 5 nós só temos um magro n = 31 , este número cresce exponencialmente com k . Também estabelece que S ( k ) ≥ 2 k - 1 (mas podemos encontrar um limite inferior melhor do que esse facilmente).

Para referência, aqui está o resultado para k = 5:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31]
[2, 6, 10, 14, 18, 22, 26, 30]
[4, 12, 20, 28]
[8, 24]
[16]

Existe uma maneira fácil de extrair um número extra: mova a metade superior dos números ímpares para qualquer outra categoria (já que a soma é maior do que qualquer número já nessa categoria) e adicione 2 ^ k à metade inferior os números ímpares. A mesma idéia provavelmente pode ser estendida para obter outros números lg k, ou talvez até outro k.
Peter Taylor

@ PeterTaylor Sim, eu percebi pouco depois de postar que isso é realmente muito trivial. É equivalente a fazer [1], [2,3], [4,5,6,7], ..., o que provavelmente é mais simples, apenas com ordem inversa de bits e bloco. É fácil ver como este pode ser estendido.
Ell
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.