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
    题解:从0开始找到M(M=sqrt(n/2)),如果有K=n-i*i,并且sqrt(k)*sqrt(k)==k的话输出即可。
    AC代码:
    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    using namespace std;
    const int maxn = 1007;
    int a[maxn];
    int n;
    int main()
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)scanf("%d",&a[i]);
        sort(a+1,a+1+n);
        int ok = 1;
        for(int i=1;i<=n;i++)
        {
            for(int j=i+1;j<=n;j++)
            {
                for(int k=j+1;k<=n;k++)
                {
                    if(a[i]+a[j]+a[k]==0)
                    {
                        ok=0;
                        cout<<a[i]<<" "<<a[j]<<" "<<a[k]<<endl;
                    }
                }
            }
        }
        if(ok)cout<<"No Solution"<<endl;
        return 0;
    }
  • 相关阅读:
    解决Cannot delete or update a parent row: a foreign key constraint fails的mysql报错
    zabbix4.2绘制网络拓扑图-添加链路速率
    zabbix 添加宏变量
    238_Product of Array Except Self
    122_Best Time to Buy and Sell Stock II
    260_Single Number III
    C# 比较时间问题
    226_Invert Binary Tree
    100_Same Tree
    283_Move Zeroes
  • 原文地址:https://www.cnblogs.com/sortmin/p/7929923.html
Copyright © 2011-2022 走看看