📌  相关文章
📜  重新排列数组,使索引相同的子集的总和与原始数组中的总和不同

📅  最后修改于: 2021-04-29 02:07:35             🧑  作者: Mango

给定一个由N个不同整数组成的数组A [] ,任务是重新排列给定数组,以使大小小于N的每个相同索引的非空子集的总和不等于其在原始数组中的总和。
例子:

方法:
这个想法是用一个较小的元素简单地替换除一个数组元素以外的所有数组元素。请按照以下步骤解决问题:

  • 将数组元素成对存储{A [i],i}
  • 按数组元素的升序对对进行排序
  • 现在,遍历排序的顺序,并将每个元素插入其下一个更大元素的原始索引(即,索引v [(i + 1)%n] .second )。这样可以确保除索引之外的每个索引现在都具有比其中存储的先前值小的元素。

下面是上述方法的实现:

C++
A[0] = 1000  B[0] = 100
A[1] = 100   B[1] = 10
A[2] = 10    B[2] = 1
A[3] = 1     B[3] = 1000


Java
{A[0], A[1]} = 1100  {B[0], B[1]} = 110
{A[0], A[2]} = 1010  {B[0], B[2]} = 101
{A[1], A[2]} = 110   {B[1], B[2]} = 11
.....
Similarly, all same-indexed subsets of size 2 have a different sum.


Python3
{A[0], A[1], A[2]} = 1110  {B[0], B[1], B[2]} = 111
{A[0], A[2], A[3]} = 1011 {B[0], B[2], B[3]} = 1101
{A[1], A[2], A[3]} = 111  {B[1], B[2], B[3]} = 1011


C#
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to rearrange the array such
// that no same-indexed subset have sum
// equal to that in the original array
void printNewArray(vector a, int n)
{
    // Initialize a vector
    vector > v;
 
    // Iterate the array
    for (int i = 0; i < n; i++) {
 
        v.push_back({ a[i], i });
    }
 
    // Sort the vector
    sort(v.begin(), v.end());
 
    int ans[n];
 
    // Shift of elements to the
    // index of its next cyclic element
    for (int i = 0; i < n; i++) {
        ans[v[(i + 1) % n].second]
            = v[i].first;
    }
 
    // Print the answer
    for (int i = 0; i < n; i++) {
        cout << ans[i] << " ";
    }
}
 
// Driver Code
int main()
{
    vector a = { 4, 1, 2, 5, 3 };
 
    int n = a.size();
 
    printNewArray(a, n);
 
    return 0;
}


输出:
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
static class pair
{
    int first, second;
     
    pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to rearrange the array such
// that no same-indexed subset have sum
// equal to that in the original array
static void printNewArray(List a, int n)
{
     
    // Initialize a vector
    List v = new ArrayList<>();
     
    // Iterate the array
    for(int i = 0; i < n; i++)
    {
        v.add(new pair(a.get(i), i));
    }
     
    // Sort the vector
    Collections.sort(v, (pair s1, pair s2) ->
    {
        return s1.first - s2.first;
    });
     
    int ans[] = new int[n];
 
    // Shift of elements to the
    // index of its next cyclic element
    for(int i = 0; i < n; i++)
    {
        ans[v.get((i + 1) % n).second] = v.get(i).first;
    }
     
    // Print the answer
    for(int i = 0; i < n; i++)
    {
        System.out.print(ans[i] + " ");
    }
}
 
// Driver Code
public static void main(String args[])
{
    List a = Arrays.asList(4, 1, 2, 5, 3);
 
    int n = a.size();
    printNewArray(a, n);
}
}
 
// This code is contributed by offbeat

时间复杂度: O(N log N)
辅助空间: O(N)