简体   繁体   English

难以理解平衡分区的逻辑

[英]Having difficulty in understanding the logic of balanced partitioning

I was solving a problem of balanced partitioning from this link . 我正在解决从此链接进行平衡分区的问题。 In this question we have to divide the array in equal parts such that the difference between their sum is least. 在这个问题中,我们必须将数组分成相等的部分,以使它们的和之间的差最小。 So, the solution I found out is considering all the cases whether a element will be included in one group or not means we have to try all 2^n cases. 因此,我发现的解决方案是考虑所有情况,是否将一个元素包含在一个组中,这意味着我们必须尝试所有2 ^ n个情况。

I came up with a solution who divided the array using bit manipulation and I am not getting the logic. 我想出了一个解决方案,该解决方案使用位操作对数组进行了划分,但我没有得到逻辑。 I am posting the code below. 我在下面发布代码。 Someone please tell me how is he dividing the array? 有人请告诉我他如何分割数组?

#include<bits/stdc++.h>
using namespace std;
#define N 11

void solve(int a[N])
{
    long long x,y,v1,v2,res,i,j;
    long long val=1<<N;
    res=INT_MAX;
    for(i=0;i<val;i++)
    {
        x=y=v1=v2=0;
        for(j=0;j<N;j++)
        {
            if(i & (1<<j))
            {
                x++;
                v1+=a[j];
            }
            else
            {
                y++;
                v2+=a[j];
            }
        }
        if(abs(x-y)<=1) res=min(res,abs(v1-v2));
    }
    cout<<res<<endl;
}
int main()
{
    int a[] = {23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4};
    solve(a);
    return 0;
}

To optimize you could try to sum the first and last element of each cicle subset, and so avoid to have cicling to all elements number of your subset but cicling only for a number of times equals to the half of your subset size.. 为了进行优化,您可以尝试对每个cicle子集的第一个元素和最后一个元素求和,因此避免对子集的所有元素进行循环运算,而仅循环进行等于子集大小一半的次数。

In your example, the external cycle iterations remain the same, while the internal are diveded by 2: 在您的示例中,外部循环迭代保持不变,而内部循环迭代为2:

(for(j=0; j<(N/2); j++)

and the sum of your grouped subset elements: 以及分组的子集元素的总和:

v(1|2)+=(a[j] + a[N-j]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM