我最近参加了一个竞赛,我被问到这个问题。给定一个长度为数组的数组,使用所有长度可以制作的最大矩形区域。可以添加长度,但不能间断。
实施例:
[ 4,2,4,4,6,8 ]
给定这个数组我们能做的最好就是制作一个像8和6这样的矩形。
给出8 * 6 = 48的区域。
我是初学者,即使经过长时间的努力思考如何做到这一点,我也无法到达任何地方。我不是在寻找解决方案,但任何能够在正确方向上推动我的线索都将受到赞赏。
TIA
编辑:有人指出(现在删除评论)很难用解释来解释解决方案,而不是发布一些代码。如有必要,请发布代码。
答案 0 :(得分:11)
问题是NP-Hard,因此backtracking解决方案[或@vhallac建议的其他指数解决方案]将是你最好的镜头,因为没有[和P!= NP,对于这类问题,没有现存的多项式解决方案。
NP-Hardness proof:
首先,我们知道矩形由4条边组成,它们成对相等[e1 = e2,e3 = e4]。
我们将证明如果这个问题存在多项式算法A
,我们也可以通过以下算法求解Partition Problem:
input: a group of numbers S=a1,a2,...,an
output: true if and only if the numbers can be partitioned
algorithm:
sum <- a1 + a2 + .. + an
lengths <- a1, a2 , ... , an , (sum*5), (sum*5)
activate A with lengths.
if A answered there is any rectangle [solution is not 0], answer True
else answer False
<强>正确性:强>
(1)如果有一个分区到S,让它为S1,S2,还有一个带边的矩形:(sum*5),(sum*5),S1,S2
,算法将产生True。
(2)如果算法产生True,则存在长度可用的矩形,因为a1 + a2 + ... + a&lt; sum * 5,有2个边长度和* 5,因为其他2个边必须使用所有剩余长度[如指定的问题],每个其他边实际上是长(a1 + a2 + ... + an)/2
,因此有问题的合法分区。
结论:有一个缩减PARTITION<=(p) this problem
,因此,这个问题是NP-Hard
修改强>
回溯解决方案非常简单,获取所有可能的矩形,并检查每个矩形以查看哪个是最好的。
回溯解决方案:伪代码:
getAllRectangles(S,e1,e2,e3,e4,sol):
if S == {}:
if legalRectangle(e1,e2,e3,e4):
sol.add((e1,e2,e3,e4))
else: //S is not empty
elem <- S[0]
getAllRectangles(S-elem,e1+elem,e2,e3,e4,sol)
getAllRectangles(S-elem,e1,e2+elem,e3,e4,sol)
getAllRectangles(S-elem,e1,e2,e3+elem,e4,sol)
getAllRectangles(S-elem,e1,e2,e3,e4+elem,sol)
getRectangle(S):
RECS <- new Set
getAllRectangles(S,{},{},{},{},RECS)
getBest(RECS)
<强> EDIT2:强>
正如评论中所讨论的,这个答案显示不仅很难找到 BEST 矩形,也很难找到 ANY 矩形,这就产生了这个问题heuristic解决方案也很难。
答案 1 :(得分:2)
这是Python中问题的一种解决方案。它根本没有优化。例如,我在检查4,2之后甚至检查2,4。但是为了展示如何找到解决方案,我认为这已经足够了。
def all_but(lst, pos):
return lst[0:pos]+lst[pos+1:]
def find_sets_with_len(segs, l):
for i in range(0, len(segs)):
val = segs[i]
if (val == l):
yield [val], all_but(segs, i)
if (val < l):
for soln, rest in find_sets_with_len(all_but(segs, i), l - val):
yield [val]+soln, rest
def find_rect(segs, l1, l2):
for side1, rest1 in find_sets_with_len(segs, l1):
for side2, rest2 in find_sets_with_len(rest1, l1):
for side3, rest3 in find_sets_with_len(rest2, l2):
return [side1, side2, side3, rest3]
def make_rect(segs):
tot_len = sum(segs)
if (tot_len %2) == 0:
opt_len=tot_len/4
for l in range(opt_len, 0, -1):
sides = find_rect(segs, l, tot_len/2-l)
if sides is not None:
print(sides)
return sides
print("Can't find any solution")
make_rect([4,2,4,4,6,8])
这个想法很简单:首先,计算最佳长度(即制作正方形的长度),然后搜索以最佳长度开始的所有内容,并向下搜索一侧的1。对于每个长度,枚举已计算长度的一侧的所有集合,然后枚举相反侧(相同长度)的所有集合,然后如果我可以找到另一个剩余长度的集合(即total_len/2
减去我正在看的边长,然后我得到了最好的解决方案。这发生在find_rect()
函数中。
答案 2 :(得分:0)
好吧,我觉得有点无聊,所以玩Java有一些经验,编码很差,没有调整,因为我想提高我的编码技能,欢迎评论。我的电脑能够回答我的小阵列:)
输出如下:
Largest rectangle range is ; 48
-------------------------------------------------
input values; [ 4,2,4,4,6,8,9 ]
-------------------------------------------------
Array details of the rectangle:
A1: [ 6 ]
B1: [ 8 ]
A2: [ 2,4 ]
B2: [ 4,4 ]
combination.class使用Kenneth算法;
import java.math.BigInteger;
public class Combination {
/**
* Burak
*/
private int[] a;
private int n;
private int r;
private BigInteger numLeft;
private BigInteger total;
public Combination (int n, int r) {
if (r > n) {
throw new IllegalArgumentException ();
}
if (n < 1) {
throw new IllegalArgumentException ();
}
this.n = n;
this.r = r;
a = new int[r];
BigInteger nFact = getFactorial (n);
BigInteger rFact = getFactorial (r);
BigInteger nminusrFact = getFactorial (n - r);
total = nFact.divide (rFact.multiply (nminusrFact));
reset ();
}
//------
// Reset
//------
public void reset () {
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
numLeft = new BigInteger (total.toString ());
}
//------------------------------------------------
// Return number of combinations not yet generated
//------------------------------------------------
public BigInteger getNumLeft () {
return numLeft;
}
//-----------------------------
// Are there more combinations?
//-----------------------------
public boolean hasMore () {
return numLeft.compareTo (BigInteger.ZERO) == 1;
}
//------------------------------------
// Return total number of combinations
//------------------------------------
public BigInteger getTotal () {
return total;
}
//------------------
// Compute factorial
//------------------
private static BigInteger getFactorial (int n) {
BigInteger fact = BigInteger.ONE;
for (int i = n; i > 1; i--) {
fact = fact.multiply (new BigInteger (Integer.toString (i)));
}
return fact;
}
//--------------------------------------------------------
// Generate next combination (algorithm from Rosen p. 286)
//--------------------------------------------------------
public int[] getNext () {
if (numLeft.equals (total)) {
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
int i = r - 1;
while (a[i] == n - r + i) {
i--;
}
a[i] = a[i] + 1;
for (int j = i + 1; j < r; j++) {
a[j] = a[i] + j - i;
}
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
}
主要是Combinator.class;
import java.util。*;
public class Combinator {
/**
* @param args
*/
private static int[] ad;
private static int[] bd;
private static String a1;
private static String a2;
private static String b1;
private static String b2;
private static int bestTotal =0;
public static void main(String[] args) {
int[] array={4,2,4,4,6,8,9};
getBestCombination(array, 1);
if(bestTotal <= 0){
System.out.println("System couldnt create any rectangle.");
}else{
System.out.println("Largest rectangle range is ; " + bestTotal);
System.out.println("-------------------------------------------------");
System.out.println("input values; " + parseArrayToString(array));
System.out.println("-------------------------------------------------");
System.out.println("Array details of the rectangle:");
System.out.println("A1: " + a1);
System.out.println("B1: " + b1);
System.out.println("A2: " + a2);
System.out.println("B2: " + b2);
}
}
private static void getBestCombination(int[] array, int level){
int[] a;
int[] b;
int bestPerimeter = getTotal(array,true);
Vector<Vector<Integer>> results = null;
for(int o=array.length-1;o>=1;o--){
for(int u=bestPerimeter;u>=1;u--){
results = Combinator.compute (array, o, u);
if(results.size() > 0){
for(int i=0;i<results.size();i++){
a = new int[results.elementAt(i).size()];
for(int j = 0;j<results.elementAt(i).size();j++){
a[j] = results.elementAt(i).elementAt(j);
}
b = removeItems(array, results.elementAt(i));
if(level == 1){
getBestCombination(a,2);
getBestCombination(b,3);
}else if(level == 2){
ad = a;
bd = b;
}else{
getBestCombination(a,4);
getBestCombination(b,4);
if(getTotal(ad, false) == getTotal(a, false) && getTotal(bd, false) == getTotal(b, false)){
if(bestTotal<(getTotal(ad, false)*getTotal(bd, false))){
bestTotal = getTotal(ad, false)*getTotal(bd, false);
a1 = parseArrayToString(ad);
a2 = parseArrayToString(a);
b1 = parseArrayToString(bd);
b2 = parseArrayToString(b);
}
}else if(getTotal(ad, false) == getTotal(b, false) && getTotal(bd, false) == getTotal(a, false)){
if(bestTotal<(getTotal(ad, false)*getTotal(bd, false))){
bestTotal = getTotal(ad, false)*getTotal(bd, false);
a1 = parseArrayToString(ad);
a2 = parseArrayToString(b);
b1 = parseArrayToString(bd);
b2 = parseArrayToString(a);
}
}
}
}
}
}
}
}
private static String parseArrayToString(int[] items){
String s = "[ ";
for(int i=0;i<items.length;i++){
if(i!=items.length-1){
s = s + items[i] + ",";
}else{
s = s + items[i];
}
}
s = s + " ]";
return s;
}
@SuppressWarnings("rawtypes")
private static int[] removeItems(int[] array, Vector items){
ArrayList<Integer> res = new ArrayList<Integer>();
for(int i=0;i<array.length;i++){
res.add(array[i]);
}
for(int u = 0;u<items.size();u++){
res.remove(items.elementAt(u));
}
int[] results = new int[res.size()];
for(int o=0;o<res.size();o++){
results[o] = res.get(o);
}
return results;
}
private static int getTotal(int[] array,boolean bestPerimeter){
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
if(bestPerimeter == true){
if(sum%2!=0){
sum = sum -1;
}
sum = sum/2;
}
//System.out.println(sum);
return sum;
}
@SuppressWarnings("rawtypes")
private static int getSum (Vector v) {
int sum = 0;
Integer n;
for (int i = 0; i < v.size (); i++) {
n = (Integer) v.elementAt(i);
sum += n.intValue ();
}
return sum;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Vector<Vector<Integer>> compute (int[] array, int atATime, int desiredTotal) {
int[] indices;
Combination gen = new Combination (array.length, atATime);
Vector results = new Vector ();
Vector combination;
int sum;
Integer intObj;
while (gen.hasMore ()) {
combination = new Vector ();
indices = gen.getNext ();
for (int i = 0; i < indices.length; i++) {
intObj = new Integer (array[indices[i]]);
combination.addElement (intObj);
}
sum = getSum (combination);
if (sum == desiredTotal) {
Collections.sort (combination);
if (!results.contains (combination)) {
results.addElement (combination);
}
}
}
return results;
}
}