排序一些苹果!


11

问题

想象一下,连续排着7个水桶。每个存储桶最多可包含2个苹果。有13个标记为1到13的苹果。它们分布在7个桶中。例如,

{5,4}, {8,10}, {2,9}, {13,3}, {11,7}, {6,0}, {12,1}

其中0代表空白。苹果 每个存储桶中的出现顺序无关紧要(例如{5,4}等同于{4,5})。

您可以将任何一个苹果从一个存储桶移动到相邻的存储桶,只要目标存储桶中有另一个苹果的空间。每一步都由您要移动的苹果的数量来描述(这是明确的,因为只有一个空白空间)。例如,应用移动

7

以上安排将导致

{5,4}, {8,10}, {2,9}, {13,3}, {11,0}, {6,7}, {12,1}

目的

编写一个程序,从STDIN读取一个排列并将其分类为以下排列

{1,2}, {3,4}, {5,6}, {7,8}, {9,10}, {11,12}, {13,0}

使用尽可能少的动作。同样,在苹果的出现顺序 每个桶是不相关的。桶的顺序很重要。它应该输出用于对用逗号分隔的每个排列进行排序的动作。例如,

13, 7, 6, ...

您的分数等于解决以下安排所需的举动总数之和:

{8, 2}, {11, 13}, {3, 12}, {6, 10}, {4, 0}, {1, 7}, {9, 5}
{3, 1}, {6, 9}, {7, 8}, {2, 11}, {10, 5}, {13, 4}, {12, 0}
{0, 2}, {4, 13}, {1, 10}, {11, 6}, {7, 12}, {8, 5}, {9, 3}
{6, 9}, {2, 10}, {7, 4}, {1, 8}, {12, 0}, {5, 11}, {3, 13}
{4, 5}, {10, 3}, {6, 9}, {8, 13}, {0, 2}, {1, 7}, {12, 11}
{4, 2}, {10, 5}, {0, 7}, {9, 8}, {3, 13}, {1, 11}, {6, 12}
{9, 3}, {5, 4}, {0, 6}, {1, 7}, {12, 11}, {10, 2}, {8, 13}
{3, 4}, {10, 9}, {8, 12}, {2, 6}, {5, 1}, {11, 13}, {7, 0}
{10, 0}, {12, 2}, {3, 5}, {9, 11}, {1, 13}, {4, 8}, {7, 6}
{6, 1}, {3, 5}, {11, 12}, {2, 10}, {7, 4}, {13, 8}, {0, 9}

是的,每种安排都有解决方案。

规则

  • 您的解决方案必须以每次移动的存储桶数的多项式时间运行。关键是要使用巧妙的启发式方法。
  • 所有算法必须是确定性的。
  • 如果出现平局,则以最短的字节数为准。

2
当只能将一个苹果移动到一个空间时,指定目的地有什么意义?
约翰·德沃夏克

如果我的蛮力解决方案在合理的时间内运行怎么办?只有7亿个州-数分钟之内即可轻松枚举。定义“合理的时间”。
约翰·德沃夏克

@JanDvorak每“有什么意义”-好电话。那不是我想到的。我在此定义的合理时间应少于暴力破解解决方案所需的时间;)
Orby 2014年

您对“合理”的定义是否意味着我们应该首先实施蛮力解决方案,然后再采用速度更快的方法?
John Dvorak 2014年

铲斗的最终订单重要吗?
AMK 2014年

Answers:


4

得分:448

我的想法是从1开始对它们进行连续排序。这为我们提供了一个不错的属性,当我们要将空间移动到上一个/下一个篮子时,我们确切地知道必须移动两个苹果中的哪个-max /最少一分钟。这是测试细目:

#1: 62     #6: 40
#2: 32     #7: 38
#3: 46     #8: 50
#4: 50     #9: 54
#5: 40    #10: 36

Total score: 448 moves

该代码可以使用很多,但是更好的代码质量将激发更多的答案。

C ++(501字节)

#include <cstdio>
#define S(a,b) a=a^b,b=a^b,a=a^b;
int n=14,a[14],i,j,c,g,p,q;
int l(int x){for(j=0;j<n;++j)if(a[j]==x)return j;}
int sw(int d){
    p=l(0);q=p+d;
    if(a[q]*d>a[q^1]*d)q^=1;
    printf("%d,", a[q]);
    S(a[q],a[p])
}
int main(){
    for(;j<n;scanf("%d", a+j),j++);
    for(;++i<n;){
        c=l(i)/2;g=(i-1)/2;
        if(c-g){
            while(l(0)/2+1<c)sw(2);
            while(l(0)/2>=c)sw(-2);
            while(l(i)/2>g){sw(2);if(l(i)/2>g){sw(-2);sw(-2);}}
        }
    }
}

进一步的改进可能是切换到C并尝试通过从较大的值开始向下(并最终将两种解决方案组合在一起)来降低得分。


1
您的代码的子字符串已经形成C程序。具体来说,只需删除第一行它就可以在C语言中工作。
feersum

@feersum你说得对。刚开始时,我有更多的C ++特定代码,但是在那之后,考虑到切换到C,看来我摆脱了它。
yasen 2014年

您能否指定您已更改解决方案中的输入格式,以使尝试验证的人更清楚?
Orby

2

C,426 448

类似于yasen的方法,这一次将苹果从1到13进行一次排序,除非每当有机会向上或向下移动较大数量的苹果时,它将采取这种方法。可悲的是,这只会提高第一个测试问题的性能,但是却有很小的提高。运行测试问题时我犯了一个错误。看来我只是简单地重新实现了yasen的方法。

#1: 62    #6: 40
#2: 32    #7: 38
#3: 46    #8: 50
#4: 50    #9: 54
#5: 40    #10: 36

它不需要大括号或逗号即可输入,例如

8 2 11 13 3 12 6 10 4 0 1 7 9 5

这是高尔夫代码,共423个字节,其中包含一些不必要的换行符(可能被高尔夫更多,但我希望这个比分能被击败):

#define N 7
#define F(x,y) for(y=0;y<N*2;y++)if(A[y]==x)break;
#define S(x,y) x=x^y,y=x^y,x=x^y;
#define C(x,y) ((A[x*2]==y)||(A[x*2+1]==y))
A[N*2],i,j,d,t,b,a,n,s,v,u,w,g;main(){for(;i<N*2;i++)scanf("%d",A+i);g=1;while
(!v){F(0,i);b=i/2;F(g,u);w=u/2;d=b<w?1:-1;n=(b+d)*2;a=(b+d)*2+1;if(A[n]>A[a])
S(n,a);t=d-1?a:n;printf("%d,",A[t]);S(A[i],A[t]);while(C((g-1)/2,g))g++;v=1;for
(j=0;j<N*2;j++)if(!C(j/2,(j+1)%(N*2)))v=0;}}

还有非高尔夫代码,它也可以打印分数:

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

#define N 7

int apples[N*2];

int find(int apple)
{
    int i;
    for (i = 0; i < N*2; i++) {
        if (apples[i] == apple)
            return i;
    }    
}

void swap(int i, int j)
{
    int temp;
    temp = apples[i];
    apples[i] = apples[j];
    apples[j] = temp;
}

int contains(int bucket, int apple)
{
    if ((apples[bucket * 2] == apple) || (apples[bucket * 2 + 1] == apple))
        return 1;
    return 0;
}

int is_solved()
{
    int i, j;
    for (i = 0; i < N * 2; i++) {
        j = (i + 1) % (N * 2);
        if (!contains(i / 2, j))
            return 0;
    }
    return 1;
}

int main()
{
    int i, j, dir, bucket, max, min, score;
    int target_i, target_bucket, target;

    /* Read the arrangement */
    for (i = 0; i < N*2; i++) {
        scanf("%d ", apples + i);
    }

    target = 1;
    while (1) {

        i = find(0);
        bucket = i / 2;
        target_i = find(target);
        target_bucket = target_i / 2;

        /* Change the direction of the sort if neccesary */
        if (bucket < target_bucket) dir = 1;
        else dir = -1;

        /* Find the biggest and smallest apple in the next bucket */
        if (apples[(bucket + dir) * 2] < apples[(bucket + dir) * 2 + 1]) {
            min = (bucket + dir) * 2;
            max = (bucket + dir) * 2 + 1;
        } else {
            min = (bucket + dir) * 2 + 1;
            max = (bucket + dir) * 2;
        }

        /* If we're going right, move the smallest apple. Otherwise move the
           biggest apple */
        if (dir == 1) {
            printf("%d, ", apples[min]);
            swap(i, min);
            score++;
        } else {
            printf("%d, ", apples[max]);
            swap(i, max);
            score++;
        }

        /* Find the next apple to sort */
        while (contains((target - 1) / 2, target))
            target++;

        /* If we've solved it then quit */
        if (is_solved())
            break;
    }
    printf("\n");
    printf("%d\n", score);
}

2

Python 3-121

这将实现深度递增的深度优先搜索,直到找到解决方案为止。它使用字典来存储访问状态,因此除非具有更高的深度窗口,否则它不会再次访问它们。在确定要检查的状态时,它使用放错位置的元素的数量作为试探法,并且仅访问可能的最佳状态。请注意,由于元素在其存储桶中的顺序无关紧要,因此它始终保持存储桶中的顺序。这使得检查元素是否放错位置更加容易。

输入是一个整数数组,第一个整数是存储桶数。

因此,例如,对于#8(这需要很长时间才能在我的计算机上运行,​​其他的只需几秒钟即可完成):

c:\python33\python.exe apples.py 7 3 4 10 9 8 12 2 6 5 1 11 13 7 0

以下是测试集上的结果:#1:12,#2:12,#3:12,#4:12,#5:11,#6:11,#7:10,#8:14,# 9:13,#10:14

这是代码:

import sys    

BUCKETS = int(sys.argv[1])    

# cleans a state up so it is in order
def compressState(someState):
  for i in range(BUCKETS):
    if(someState[2*i] > someState[2*i + 1]):
      temp = someState[2*i]
      someState[2*i] = someState[2*i + 1]
      someState[2*i + 1] = temp
  return someState    

state = compressState([int(x) for x in sys.argv[2:]])
print('Starting to solve', state)
WINNINGSTATE = [x for x in range(1, BUCKETS*2 - 1)]
WINNINGSTATE.append(0)
WINNINGSTATE.append(BUCKETS*2 - 1)
maxDepth = 1
winningMoves = []
triedStates = {}    

# does a depth-first search
def doSearch(curState, depthLimit):
  if(curState == WINNINGSTATE):
    return True
  if(depthLimit == 0):
    return False
  myMoves = getMoves(curState)
  statesToVisit = []
  for move in myMoves:
    newState = applyMove(curState, move)
    tns = tuple(newState)
    # do not visit a state again unless it is at a higher depth (more chances to win from it)
    if(not ((tns in triedStates) and (triedStates[tns] >= depthLimit))):
      triedStates[tns] = depthLimit
      statesToVisit.append((move, newState[:], stateScore(newState)))
  statesToVisit.sort(key=lambda stateAndScore: stateAndScore[2])
  for stv in statesToVisit:
    if(stv[2] > statesToVisit[0][2]):
      continue
    if(doSearch(stv[1], depthLimit - 1)):
      winningMoves.insert(0, stv[0])
      return True
  return False    

# gets the moves you can make from a given state
def getMoves(someState):
  # the only not-allowed moves involve the bucket with the 0
  allowedMoves = []
  for i in range(BUCKETS):
    if((someState[2*i] != 0) and (someState[2*i + 1] != 0)):
      allowedMoves.append(someState[2*i])
      allowedMoves.append(someState[2*i + 1])
  return allowedMoves    

# applies a move to a given state, returns a fresh copy of the new state
def applyMove(someState, aMove):
  newState = someState[:]
  for i in range(BUCKETS*2):
    if(newState[i] == 0):
      zIndex = i
    if(newState[i] == aMove):
      mIndex = i
  if(mIndex % 2 == 0):
    newState[mIndex] = 0
  else:
    newState[mIndex] = newState[mIndex-1]
    newState[mIndex-1] = 0
  newState[zIndex] = aMove
  if((zIndex % 2 == 0) and (newState[zIndex] > newState[zIndex+1])):
    newState[zIndex] = newState[zIndex+1]
    newState[zIndex+1] = aMove
  return newState    

# a heuristic for how far this state is from being sorted
def stateScore(someState):
  return sum([1 if someState[i] != WINNINGSTATE[i] else 0 for i in range(BUCKETS*2)])    

# go!
while(True):
  triedStates[tuple(state)] = maxDepth
  print('Trying depth', maxDepth)
  if(doSearch(state, maxDepth)):
    print('winning moves are: ', winningMoves)
    break
  maxDepth += 1

我赞成这一点,因为它对于查看最佳解决方案很有用,但是请注意,按问题的要求,此操作并不能在多项式时间内以每次移动的存储桶数运行。我不认为任何产生最佳解决方案的算法都可以在多项式时间内运行。
Orby 2014年

对于第一个测试问题,您的程序生成10、8、1、12、6、7、11、3、5、13、4、9,这不是有效的解决方案。我认为您可能误解了这个问题。请注意该问题指出“您可以将任何苹果从一个存储桶移动到相邻存储桶”,即该存储桶在其右侧或左侧(不是任意存储桶)。
Orby 2014年

哦,我完全错过了邻接限制!发布此消息后,我一直怀疑运行时间限制也被违反。我在编写时并不确定100%,因为避免重复状态的动态编程元素使我感到困惑。感谢您的支持,尽管这在两个方面都失败了;这是一个有趣的难题,我将看看是否能提出一个更好,有效的答案。
RT
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.