N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.

  • N개의 자연수 중에서 M개를 고른 수열

입력

첫째 줄에 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8)

둘째 줄에 N개의 수가 주어진다. 입력으로 주어지는 수는 10,000보다 작거나 같은 자연수이다.

출력

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다.

수열은 사전 순으로 증가하는 순서로 출력해야 한다.

예제 입력 1

3 1
4 4 2

예제 출력 1

2
4

예제 입력 2

4 2
9 7 9 1

예제 출력 2

1 7
1 9
7 1
7 9
9 1
9 7
9 9

예제 입력 3

4 4
1 1 1 1

예제 출력 3

1 1 1 1

더보기

Solution

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

int *A=NULL, *B=NULL, N, M, history[40320][8], count=0;

void N_M(int m,bool *used)
{
	if(m==M)
	{
		bool same=true;

		for(int i=0;i<count;i++)
		{
			bool same=true;

			for(int j=0;j<M;j++)
				if(B[j]!=history[i][j])
				{
					same=false;
					break;
				}
			if(same)
				return;
		}

		for(int i=0;i<M;i++)
			history[count][i]=B[i];
		count++;
		return;
	}

	for(int i=0;i<N;i++)
		if(!used[i])
		{
			B[m]=A[i];
			used[i]=true;
			N_M(m+1,used);
			used[i]=false;
		}
}

int main(void)
{
	scanf("%d%d", &N, &M);

	A=(int *)malloc(N*sizeof(int));
	B=(int *)malloc(M*sizeof(int));
	bool *used=(bool *)calloc(M,sizeof(bool));

	for(int n=0;n<N;n++)
		scanf("%d", &A[n]);

	for(int i=0;i<N;i++)
		for(int j=i+1;j<N;j++)
			if(A[i]>A[j])
			{
				A[i]+=A[j];
				A[j]=A[i]-A[j];
				A[i]-=A[j];
			}

	N_M(0,used);

	for(int i=0;i<count;i++)
		for(int j=i+1;j<count;j++)
			for(int k=0;k<M;k++)
				if(history[i][k]>history[j][k])
					for(int l=0;l<M;l++)
					{
						history[i][k]+=history[j][k];
						history[j][k]=history[i][k]-history[j][k];
						history[i][k]-=history[j][k];
					}
				else if(history[i][k]<history[j][k])
					break;

	for(int i=0;i<count;i++)
	{
		for(int j=0;j<M;j++)
			printf("%d ", history[i][j]);
		printf("\n");
	}
	free(A);
	free(B);
	free(used);
	return 0;
}
728x90

+ Recent posts