zoukankan      html  css  js  c++  java
  • POJ 2785 4 Values whose Sum is 0

    Description

    The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) ∈ A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n .

    Input

    The first line of the input file contains the size of the lists n (this value can be as large as 4000). We then have n lines containing four integer values (with absolute value as large as 228 ) that belong respectively to A, B, C and D .

    Output

    For each input file, your program has to write the number quadruplets whose sum is zero.

    Sample Input

    6

    -45 22 42 -16

    -41 -27 56 30

    -36 53 -37 77

    -36 30 -75 -46

    26 -38 -10 62

    -32 -54 -6 45

    Sample Output

    5

    Hint

     

    Sample Explanation: Indeed, the sum of the five following quadruplets is zero: (-45, -27, 42, 30), (26, 30, -10, -46), (-32, 22, 56, -46),(-32, 30, -75, 77), (-32, -54, 56, 30).

    【代码】:

    【Time】:O(N²logN)

    #include <iostream>
    #include <algorithm>
    #include<cstdio>
    using namespace std;
    #define N 4005
    
    int n, a[N], b[N], c[N], d[N], cd[N*N];
    int main()
    {
        cin >> n;
         for(int i = 0;i < n; i++)
            scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
    
         for(int i = 0;i < n; i++){
             for(int j = 0;j < n; j++){
                cd[i*n+j] = c[i] + d[j];
            }
        }
        sort(cd,cd+n*n);
        long long ans = 0;
         for(int i = 0;i < n; i++){
             for(int j = 0;j < n; j++){
                int x = -(a[i] + b[j]);
                ans += upper_bound(cd, cd+n*n, x) - lower_bound(cd, cd+n*n, x);
            }
        }
        cout << ans << endl;
        return 0;
    }
    /*
    6
    -45 -41 -36 -36 26 -32
    22 -27 53 30 -38 -54
    42 56 -37 -75 -10 -6
    -16 30 77 -46 62 45
    */
  • 相关阅读:
    jsp页面中使用 splitfn:split注意事项
    【SQL】- 基础知识梳理(二)
    【SQL】- 基础知识梳理(一)
    面向对象编程思想-解释器模式
    NPOI操作Excel
    面向对象编程思想-备忘录模式
    面向对象编程思想-访问者模式
    面向对象编程思想-责任链模式
    面向对象编程思想-策略模式
    面向对象编程思想-状态模式
  • 原文地址:https://www.cnblogs.com/Roni-i/p/8764826.html
Copyright © 2011-2022 走看看