zoukankan      html  css  js  c++  java
  • 51nod 1090 3个数和为0【二分】

    基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
     收藏
     关注
    给出一个长度为N的无序数组,数组中的元素为整数,有正有负包括0,并互不相等。从中找出所有和 = 0的3个数的组合。如果没有这样的组合,输出No Solution。如果有多个,按照3个数中最小的数从小到大排序,如果最小的数相等则按照第二小的数排序。
     
    Input
    第1行,1个数N,N为数组的长度(0 <= N <= 1000)
    第2 - N + 1行:A[i](-10^9 <= A[i] <= 10^9)
    Output
    如果没有符合条件的组合,输出No Solution。
    如果有多个,按照3个数中最小的数从小到大排序,如果最小的数相等则继续按照第二小的数排序。每行3个数,中间用空格分隔,并且这3个数按照从小到大的顺序排列。
    Input示例
    7
    -3
    -2
    -1
    0
    1
    2
    3
    Output示例
    -3 0 3
    -3 1 2
    -2 -1 3
    -2 0 2
    -1 0 1

    【分析】:直接枚举两个数,二分查找第三个数就行了。由于题中要求按数的大小排序输出,所以直接sort升序输出即可,这样即可用二分查找第三个数,即-a[i]-a[j],并且一定比a[i]和a[j]大,复杂度为n^2log(n);
    【代码】:
    #include <bits/stdc++.h>
    
    using namespace std;
    
    const int maxn = 1000+10;
    int n;
    int a[maxn];
    
    int check(int x)
    {
        int l=0,r=n-1;
        while(l<=r)
        {
            int mid=(l+r)>>1;
            if(a[mid]==x)
                return 1;
            if(a[mid]<x)
                l=mid+1;
            else
                r=mid-1;
        }
        return 0;
    
    }
    int main()
    {
        int ans;
        int flag=0;
    
        cin>>n;
        for(int i=0;i<n;i++)
            cin>>a[i];
        sort(a,a+n);
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                int ans=-a[i]-a[j];
                if(ans<=a[j])
                    break;
                if(check(ans))
                {
                    cout<<a[i]<<" "<<a[j]<<" "<<ans<<endl;
                    flag=1;
                }
    
            }
        }
        if(!flag)
            cout<<"No Solution"<<endl;
        return 0;
    }
    二分
    #include <bits/stdc++.h>
    
    using namespace std;
    const int maxn = 1000+10;
    int main()
    {
        int n;
        int flag=1;
        int a[maxn];
        cin>>n;
        for(int i=0;i<n;i++)
            cin>>a[i];
        sort(a,a+n);
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                if(a[i]+a[j]<=0)
                {
                    for(int k=j+1;k<n;k++)
                    {
                        if(a[i]+a[j]+a[k]==0)
                        {
                            cout<<a[i]<<" "<<a[j]<<" "<<a[k]<<endl;
                            flag=0;
                        }
                    }
                }
            }
        }
        if(flag)
            cout<<"No Solution"<<endl;
        return 0;
    }
    暴力枚举+剪枝
  • 相关阅读:
    安装 elasticsearch For LINUX
    java 读取文件最佳实践
    mysql alter 语句用法,添加、修改、删除字段等
    Linux type命令
    在mahout安装目录下输入mahout 提示 ERROR: Could not find mahout-examples-*.job
    Ubuntu中安装eclipse ,双击eclipse出现invalid configuration location问题
    Ubuntu中查看32还是64
    转载--JAVA读取文件最佳实践
    Ubuntu中添加eclipse
    Hadoop 如何查看是否32位
  • 原文地址:https://www.cnblogs.com/Roni-i/p/7767959.html
Copyright © 2011-2022 走看看