Cod sursa(job #465655)

Utilizator SmarandaMaria Pandele Smaranda Data 25 iunie 2010 11:14:21
Problema Ratphu Scor 40
Compilator cpp Status done
Runda Stelele Informaticii 2010, gimnaziu si clasa a IX-a, Ziua 1 Marime 1.51 kb
#include<stdio.h>
#include<string.h>
char n[20];
long u;
char nr[20];
long st[20];
long impartirea (long p)
{
	long d,r;
	long i;
	r=0;
	for (i=0;i<=u;i++)
	{
		d=r*10+nr[i]-48;
		r=d%p;
	}
	return r;
}

int main()
{
	long l,gata,i,j,aux,min,poz,stt,dr,pcif,p,r,num=0;
	
	freopen("ratphu.in","r",stdin);
	freopen("ratphu.out","w",stdout);
	
	scanf("%s",n);
	scanf("%ld",&p);
	l=strlen(n);
	for (i=1;i<=l;i++)
		st[i]=i;
	pcif=0;
			u=-1;
			nr[0]=NULL;
			for (i=1;i<=l;i++)
			{
				if (!(pcif==0 && n[st[i]-1]==0))
				{
					nr[++u]=n[st[i]-1];
					if (u==0)
						pcif=1;
				}
				else
					if (pcif==1)
					{
						nr[++u]=n[st[i]-1];
					}
			}
			r=impartirea(p);
			if (r==0)
				num++;
	gata=0;
	while (!gata)
	{
		for (i=l-1;i>=1;i--)
			if (st[i]<st[i+1])
				break;
		if (i<1)
			gata=1;
		else
		{
			min=2000000;
			for (j=i+1;j<=l;j++)
			{
				if (st[j]<min && st[j]>st[i])
					{
						min=st[j];
						poz=j;
					}
			}
			aux=st[i];
			st[i]=st[poz];
			st[poz]=aux;
			stt=i+1;
			dr=l;
			while (stt<dr)
			{
				aux=st[stt];
				st[stt]=st[dr];
				st[dr]=aux;
				stt++;
				dr--;
			}
			pcif=0;
			u=-1;
			nr[0]=NULL;
			for (i=1;i<=l;i++)
			{
				if (!(pcif==0 && n[st[i]-1]==0))
				{
					nr[++u]=n[st[i]-1];
					if (u==0)
						pcif=1;
				}
				else
					if (pcif==1)
					{
						nr[++u]=n[st[i]-1];
					}
			}
			r=impartirea(p);
			if (r==0)
				num++;
		}
	}
	printf("%ld\n",num);
	return 0;
}