Cod sursa(job #678460)

Utilizator ktalyn93Catalin ktalyn93 Data 11 februarie 2012 19:21:49
Problema Generare de permutari Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <stdio.h>
int n,st[20];
bool gata;
void switchh(int a,int b)
{
	int c=st[a];
	st[a]=st[b];
	st[b]=c;
}
int min(int p)
{
	int minn=99,pos;
	for(int i=p+1;i<=n;i++)
		if(st[i]>st[p] && st[i]<minn)
		{	
			minn=st[i];
			pos=i;
		}
	return pos;
}
void nextperm()
{
		
	int i;
	if (gata)
	{	
		for(i=1;i<=n;i++){ st[i]=i;
		printf("%d ",st[i]);}
		printf("\n");
		gata=false;
	}
	for(i=n-1;st[i+1]<st[i];i--);
	if (i==0)
		gata=true;
	else
	{
	switchh(i,min(i));
	for(int j=1;j<=n/2;j++)
		switchh(j+i,n-j+1);
	}
}
int main()
{
	freopen("permutari.in","r",stdin);
	freopen("permutari.out","w",stdout);
	scanf("%d",&n);
	gata=true;
	do
	{	
		nextperm();
		if (!gata)
			for(int i=1;i<=n;i++)
				printf("%d ",st[i]);
		    printf("\n");
	}while(!gata);
	return 0;
}