Cod sursa(job #1377270)

Utilizator dnprxDan Pracsiu dnprx Data 5 martie 2015 20:58:11
Problema Multiplu Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.07 kb
#include <fstream>
#include <iostream>
#include <stack>
#define Nmax 2000002

using namespace std;

int M;
bool t[Nmax], r[Nmax];
int pred[Nmax], q[Nmax];
stack <char> st;

int Cmmdc(int a, int b)
{
    int r;
    while (b != 0)
    {
        r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int Cmmmc(int a, int b)
{
    int c = Cmmdc(a, b);
    return (a / c) * b;
}

void Citire()
{
    int x, y;
    ifstream fin("multiplu.in");
    fin >> x >> y;
    fin.close();
    M = Cmmmc(x, y);
}

void Rezolvare()
{
    int x, pr, ul, rest, i;
    bool gata;
    x = 1;
    pr = ul = 0;
    q[ul] = x;
    r[1] = true;
    pred[0] = -1;
    t[0] = true; // e cifra 1
    gata = false;
    while (!gata)
    {
        x = q[pr];
        i = pr;
        pr++;
        rest = (x * 10) % M;
        if (rest == 0)
        {
            gata = true;
            q[++ul] = rest;
            pred[ul] = i;
            t[ul] = false;
        }
        else
        {
            if (!r[rest])
            {
                q[++ul] = rest;
                pred[ul] = i;
                r[rest] = true;
                t[ul] = false;
            }
        }

        if (!gata)
        {
            rest = (x * 10 + 1) % M;
            if (rest == 0)
            {
                gata = true;
                q[++ul] = rest;
                pred[ul] = i;
                t[ul] = true;
            }
            else
            {
                if (!r[rest])
                {
                    q[++ul] = rest;
                    pred[ul] = i;
                    r[rest] = true;
                    t[ul] = true;
                }
            }
        }
    }
    // drumul
    i = ul;
    while (i != -1)
    {
        if (t[i]) st.push('1');
        else st.push('0');
        i = pred[i];
    }
    ofstream fout("multiplu.out");
    while (!st.empty())
    {
        fout << st.top();
        st.pop();
    }
    fout.close();
}

int main()
{
    Citire();
    Rezolvare();
    return 0;
}