加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

POJ PKU 2549 二分

(2010-04-29 16:00:32)
标签:

poj

pku

2549

it

分类: 杂题

题目描述:

给你一个集合,让你从中找出4个不同的数字a, b, c, d。满足a b c = d。

找出最大的d。

解题报告:

首先把任意两两组合可能的和存到数组y中,y需要n^2的大小。

把y排序后,然后再枚举任意两两组合d,c,二分搜索d - c是不是在y中,并判断合理性即可。

时间复杂度:

n^2 log(n^2)

代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int n, x[1000], cnt;
struct q{int num, a, b;}y[1000000];
bool cmp(q a, q b){return a.num < b.num;}
bool search(int d, int c)
{
    int l = 0, r = cnt - 1;
    while(l <= r)
    {
        int mid = (l r) / 2;
        if (y[mid].num == d - c)
        {
            for(int i = mid; i < cnt && y[i].num == d - c; i )
                if (y[i].a != d && y[i].a != c && y[i].b != d && y[i].b != c)
                    return true;
            for(int i = mid - 1; i >= 0 && y[i].num == d - c; i--)
                if (y[i].a != d && y[i].a != c && y[i].b != d && y[i].b != c)
                    return true;
            return false;
        }
        else if (y[mid].num > d - c) r = mid - 1;
        else l = mid 1;
    }
    return false;
}
int main()
{
    while(scanf("%d", &n) && n)
    {
        for(int i = 0; i < n; i )
            scanf("%d", &x[i]);
        sort(x, x n);
        cnt = 0;
        for(int i = 0; i < n; i )
            for(int j = i 1; j < n; j )
                if (x[i] != x[j])
                {
                    y[cnt].a = x[i];y[cnt].b = x[j];y[cnt].num = x[i] x[j];
                    cnt ;
                }
        sort(y, y cnt, cmp);
        int ans = -2000000000;
        for(int i = n - 1; i >= 0; i--)
            for(int j = i - 1; j >= 0; j--)
            {
                if (x[i] != x[j] && x[i] > ans)
                {
                    if (search(x[i], x[j]))
                        ans = x[i];
                }
            }
        if (ans == -2000000000)
            printf("no solution\n");
        else
            printf("%d\n", ans);
    }
    return 0;
}

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有