首页 > 其他 > 详细

UVA10483 - The Sum Equals the Product(枚举)

时间:2014-08-18 20:29:42      阅读:340      评论:0      收藏:0      [点我收藏+]

题目链接


题意:在实数a,b之间找到一个数c(最多到小数点的后两位),找出存在c = x + y + z = x * y * z,按字典序输出。

思路:先将数都扩大100倍,方便计算。但直接枚举所有情况的话会TLE,所以我们要缩小枚举范围。先枚举x,因为x,y,z要按照非递减顺序,所以x * x * x必须要小于c * 10000,再枚举y,同理可的x * y * y也必须小于c * 10000,至于z可以由公式(x + y + z)* 10000 = x * y * z得到,所以z = (x + y) * 10000 / (x * y - 10000)。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int MAXN = 10000;

struct state{
    double sum, x, y, z;
}ans[MAXN];

double a, b;
int n, m, cnt;

int cmp(state a, state b) {
    if (a.sum != b.sum)
        return a.sum < b.sum;
    if (a.x != b.x)
        return a.x < b.x;
    if (a.y != b.y)
        return a.y < b.y;
    if (a.z != b.z)
        return a.z < b.z;
}

int judge(int i, int j, int k) {
    int sum = i + j + k;
    int mul = i * j * k;
    if (sum != mul / 10000)
        return false;
    if (mul % 10000)
        return false;
    mul /= 10000;
    if (sum < n || sum > m || mul < n || mul > m)
        return false;
    return true;    
}

void outPut() {
    sort(ans, ans + cnt, cmp);
    for (int i = 0; i < cnt; i++)
        printf("%.2lf = %.2lf + %.2lf + %.2lf = %.2lf * %.2lf * %.2lf\n", 
                ans[i].sum, ans[i].x, ans[i].y, ans[i].z, ans[i].x, ans[i].y , ans[i].z);
}

int main() {
    while (scanf("%lf%lf", &a, &b) != EOF) {
        n = (int)(a * 100); 
        m = (int)(b * 100); 
        cnt = 0;
        for (int i = 1; (i * i * i) <= m * 10000; i++) {
            for (int j = i; (i * j * j) <= m * 10000; j++) {
                int sum = i + j; 
                int mul = i * j;
                if (mul <= 10000)
                    continue;
                int k = sum * 10000 / (mul - 10000);
                if (k < j)
                    continue;
                if (!judge(i, j, k))
                   continue;
                ans[cnt].sum = (i * j * k * 1.0) / 1000000;
                ans[cnt].x = (i * 1.0) / 100;
                ans[cnt].y = (j * 1.0) / 100;
                ans[cnt].z = (k * 1.0) / 100;
                cnt++;
            } 
        } 
        outPut();
    }     
    return 0;
}



UVA10483 - The Sum Equals the Product(枚举),布布扣,bubuko.com

UVA10483 - The Sum Equals the Product(枚举)

原文:http://blog.csdn.net/u011345461/article/details/38665273

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!