Cod sursa(job #1834224)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 24 decembrie 2016 06:23:37
Problema Ecuatie Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.75 kb
#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using ld = long double;

vector<ll> all_divs(ll x){
	x = max(x, -x);
	vector<ll> rez;
	for(ll i = 1; i*i <= x; ++i){
		if(x%i) continue;
		rez.push_back(i);
		rez.push_back(-i);
		rez.push_back(x/i);
		rez.push_back(-x/i); }
	sort(begin(rez), end(rez));
	rez.erase(unique(begin(rez), end(rez)), end(rez));
	return rez; }

struct a_solution{
	ll p1, q1, p2, q2;
	a_solution(const ld x, const ld y, const ld z, const ld p):
		p1(round(x)), q1(round(y)), p2(round(z)), q2(round(p)){}
	bool operator<(const a_solution& rhs)const{
		return p1 < rhs.p1 || (p1 == rhs.p1 && q1 < rhs.q1); }
	bool operator==(const a_solution& rhs)const{
		return p1 == rhs.p1 && q1 == rhs.q1 && p2 == rhs.p2 && q2 == rhs.q2; } };

void print_paren(ostream& lhs, const ll p, const ll q){
	lhs << '(';
	if(p == 1);
	else if(p == -1) lhs << '-';
	else lhs << p;
	lhs << 'x';
	if(q >= 0) lhs << '+';
	lhs << q;
	lhs << ')'; }
ostream& operator<<(ostream& lhs, const a_solution& rhs){
    print_paren(lhs, rhs.p1, rhs.q1);
    print_paren(lhs, rhs.p2, rhs.q2);
    return lhs; }
bool whole(ld x){
	return x == round(x); }

int main(){
	ifstream f("ecuatie.in");
	ofstream g("ecuatie.out");
	ll a, b, c;
	f >> a >> b >> c;

	vector<ll> divs = all_divs(a);
	vector<a_solution> sols;

	const ld delta = (ld)b * b - (ld)a * c * 4ll,
		x1 = (-(ld)b + sqrt(delta)) / ((ld)a * 2), x2 = (-(ld)b - sqrt(delta)) / ((ld)a * 2);
	
	for(const auto tmp : divs){
		const ld m1 = tmp, m2 = a / m1;

		if(whole(m1 * x1) && whole(m2 * x2)){
			sols.emplace_back(m1, -m1 * x1, m2, -m2 * x2); } }
	
	sort(begin(sols), end(sols));
	sols.erase(unique(begin(sols), end(sols)), end(sols));

	ll k;
	f >> k;

	--k;

	if(k >= sols.size()) g << -1;
	else g << sols[k];

	return 0; }