Как напечатать подмножества (наборы мощности) массива, состоящего из целых чисел в лексикографическом порядке c на языке c? - PullRequest
0 голосов
/ 21 февраля 2020

Учитывая массив уникальных целочисленных элементов, выведите все подмножества данного массива в лексикографическом порядке.

Формат ввода

Первая строка ввода содержит T - количество тестовых случаев. За ним следуют 2T строк, первая строка содержит N - размер массива, а вторая строка содержит элементы массива.

Ограничения

1 <= T <= 100 </p>

1 <= N <= 10 </p>

0 <= A [i] <= 100 </p>

Формат вывода

Для каждого теста выведите подмножества данный массив в лексикографическом порядке, разделенный новой строкой. Выведите дополнительную новую строку между выводами различных тестовых случаев.

void solve()
{
    int n;
    scanf("%d",&n);
    int a[n];
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    merge_sort(a,0,n-1);//for sorting, not given here
    for(int i=0;i<(1<<n);i++)
    {
        for(int j=0;j<n;j++)
        {
            if((i&(1<<j))>0)
                printf("%d ",a[j]);
        }
        printf("\n");
    }
}
What shall I do after this should I use a 2d array? if so how?
>
> Sample Input 0
> 
> 3(no.of test cases)
>
> 3(size)
>
> 5 15 3(input elements)
> 
> 2
> 
>57 96
>
> 4
>
>3 15 8 23
> 
> 
>## Expected output## 

3 
3 5  
3 5 15  
3 15  
5  
5 15 
15 

57
57 96  
96  

3  
3 8  
3 8 15  
3 8 15 23  
3 8 23  
3 15  
3 15 23  
3 23 
8  
8 15 
8 15 23  
8 23  
15  
15 23  
23

1 Ответ

0 голосов
/ 03 марта 2020

ОТВЕТЬ НА ЭТОТ

Без использования рекурсии

этот код все еще может быть оптимизирован, любая помощь при этом будет очень полезно.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void solve();
void merge(int a[],int s,int e);
void merge_sort(int a[],int s,int e);
int indexSearcher(int a[],int b[],int h,int i);
int main() {
int t;
    scanf("%d",&t);/* This is for printing testcases*/
    while(t--)
    {
        solve();
        printf("\n");
    }
    return 0;
}
    int compare(const void *a, const void *b) {
return(*(int*)a > *(int*)b);
}
void solve()
{
    int n;
    scanf("%d",&n);
    int a[n+1],main_a[n];
    a[n]=-1;



for(int i=0;i<n;i++)
{
    scanf("%d",&main_a[i]);

}
qsort(main_a, n, sizeof(int), compare);//for sorting
    /* loading all the elements to another array so that it won't miss its original  
      sorted order and it is used as reference*/
    for(int e=0;e<n;e++){
        a[e]=main_a[e];
    }


int j=0;
int i=0;
for( j=0;j<n;j++){
for( i=0;i<=j;i++)
printf("%d ",a[i]);//This can be optimized also.
    printf("\n");
}
    a[i]=-1;// the invalid value is replaced by -1 every time
    int u=i;//assigning or updating u to last valid index every time

    while(a[0]!=main_a[n-1]){    
if(a[u-1]==main_a[n-1]) 
 /* If we reach last index every time the penultimate index is updated to it's corresponding consecutive index (successor).*/
{
    u=0;
    while(a[u]!=-1)
    u++;


    a[u-2]=indexSearcher(a,main_a,a[u-2],n);//gives the successor of the penultimate index
    a[u-1]=-1;
    for (j=0;j<=u-2;j++){
        printf("%d ",a[j]);
    }
     u=0;
    while(a[u]!=-1)
    u++;
    //printer(a,i-1);
    printf("\n");
}

else if(a[u-1]!=main_a[n-1])
  /*If we don't reach the last index we print until we get there every time in a  new line by updating the index by 1 */
{
    u=0;
    while(a[u]!=-1)
    u++;
    a[u]=indexSearcher(a,main_a,a[u-1],n);/*here we get the correct lexical value
      i.e., the element which should come after the current element in lexical order.*/
    a[u+1]=-1;
    for (j=0;j<u+1;j++){
        printf("%d ",a[j]);
    }
     u=0;
    while(a[u]!=-1)
    u++;

    printf("\n");
}
}

}

int indexSearcher(int a[],int main_a[],int s,int n)
{
    for(int i=0;i<n;i++){
    if(s==main_a[i]){
    return main_a[i+1];
    }
    }
    return 0; 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...