Cod sursa(job #798524)

Utilizator vladstoickvladstoick vladstoick Data 16 octombrie 2012 18:45:32
Problema Multiplu Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.51 kb

#include<fstream>
#include<queue>
using namespace std;
ifstream in ("multiplu.in");
ofstream out("multiplu.out");
queue <int > coada;
int a , b, nr;
const int N = 2000002;
int u[N],pred[N],viz[N];
int cmmc(int a,int b)
{
    int c=0;
    int prod=a*b;
    while (b) {
        c = a % b;
        a = b;
        b = c;
    }
    return prod/a;
}
void recupereaza()
{
    int a[100001];
    a[0]=0;
    int poz=0;
    while(pred[poz]!=0)
    {
        a[++a[0]]=u[poz];
        if(pred[poz]==0)
            break;
        poz=pred[poz];
    }
    a[++a[0]]=u[poz];
    for(int i=a[0];i>=1;i--)
        out<<a[i];
}
void solve()
{
    if(nr==1)
    {
        out<<"1";
        return;
    }
    u[1]=1;
    viz[1]=1;
    coada.push(1);
    while(!coada.empty())
    {
        int curentRest=coada.front();
        if(curentRest==0)
        {
            recupereaza();
            return;
        }
        int newRest;
        coada.pop();
        //adaugam un 1
        newRest=(curentRest*10+1)%nr;
        if(viz[newRest]==0)
        {
            viz[newRest]=1;
            u[newRest]=1;
            pred[newRest]=curentRest;
            coada.push(newRest);
        }
        newRest=(curentRest*10)%nr;
        if(viz[newRest]==0)
        {
            viz[newRest]=1;
            u[newRest]=0;
            pred[newRest]=curentRest;
            coada.push(newRest);
        }
    }
}
int main()
{
    in>>a>>b;
    nr=cmmc(a,b);
    solve();
    return 0;
}