Cod sursa(job #1609633)

Utilizator Athena99Anghel Anca Athena99 Data 22 februarie 2016 21:56:37
Problema Ecuatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.68 kb
#include <algorithm>
#include <cmath>
#include <fstream>
#include <vector>

using namespace std;

ifstream fin("ecuatie.in");
ofstream fout("ecuatie.out");

int a, b, c, k;
double x1, x2;

struct str {
    int p1, p2, q1, q2;
};

vector <str> v;

inline str mp( int p1, int p2, int q1, int q2 ) {
    str sol;
    sol.p1= p1, sol.p2= p2, sol.q1= q1, sol.q2= q2;

    return sol;
}

void check( int x ) {
    int auxq1= (double)x*x1, auxq2= (double)a/x*x2;
    if ( (double)auxq1==(double)x*x1 && (double)auxq2==(double)a/x*x2 ) {
        v.push_back(mp(x, a/x, -auxq1, -auxq2));
        v.push_back(mp(a/x, x, -auxq2, -auxq1));
    }

    auxq1= (double)x*x2, auxq2= (double)a/x*x1;
    if ( (double)auxq1==(double)x*x1 && (double)auxq2==(double)a/x*x2 ) {
        v.push_back(mp(x, a/x, -auxq1, -auxq2));
        v.push_back(mp(a/x, x, -auxq2, -auxq1));
    }
}

bool cmp( str x, str y ) {
    if ( x.p1!=y.p1 ) {
        return x.p1<y.p1;
    } else {
        if ( x.q1!=y.q1 ) {
            return x.q1<y.q1;
        } else {
            if ( x.p2!=y.p2 ) {
                return x.p2<y.p2;
            } else {
                return x.q2<y.q2;
            }
        }
    }
}

int main(  ) {
    fin>>a>>b>>c>>k;

    int delta= (b*b-4*a*c), sqr;
    sqr= sqrt(delta);
    if ( delta<0 || sqr*sqr!=delta ) {
        fout<<"-1";
        return 0;
    }
    x1= ((double)-b+sqr)/a/2, x2= ((double)-b-sqr)/a/2;

    int newa= a;
    if ( newa<0 ) {
        newa= -newa;
    }
    int sqra= sqrt(newa);
    for ( int i= 1; i<=sqra; ++i ) {
        if ( a%i==0 ) {
            check(i);
            check(-i);
            check(a/i);
            check(-a/i);
        }
    }

    sort( v.begin(), v.end(), cmp );
    for ( vector <str>::iterator it= v.begin(), it2; it!=v.end(); ++it ) {
        it2= it;
        ++it2;
        if ( it2!=v.end() ) {
            if ( (*it2).p1==(*it).p1 && (*it2).p2==(*it).p2 && (*it2).q1==(*it).q1 && (*it2).q2==(*it).q2 ) {
                v.erase(it2);
            }
        }
    }

    if ( (int)v.size()<k ) {
        fout<<"-1\n";
        return 0;
    }
    --k;
    fout<<"(";
    if ( v[k].p1==-1 ) {
        fout<<"-x";
    } else if ( v[k].p1!=1 ) {
        fout<<v[k].p1<<"x";
    } else {
        fout<<"x";
    }

    if ( v[k].q1<0 ) {
        fout<<v[k].q1<<")(";
    } else {
        fout<<"+"<<v[k].q1<<")(";
    }
    if ( v[k].p2==-1 ) {
        fout<<"-x";
    } else if ( v[k].p2!=1 ) {
        fout<<v[k].p2<<"x";
    }
    if ( v[k].q2<0 ) {
        fout<<v[k].q2<<")";
    } else {
        fout<<"+"<<v[k].q2<<")";
    }

    fout<<"\n";

    return 0;
}