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

    4 Values whose Sum is 0
    链接:http://poj.org/problem?id=2785
    Time Limit: 15000MS   Memory Limit: 228000K
         
    Case Time Limit: 5000MS

    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).
    题意:ABCD四个集合,每个集合选一个数,使之加起来=0;
    题解:二分,得到出AB组合, CD组合的所有请况,把得到的和排序,双指针使之加起来=0;
    #include<cstdio>
    #include<iostream>
    #include<cstdlib>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    // 0--n-1 1   n -- 2n-1 0
    const int M = 4005, inf = 1e8;
    int ans, a[M], b[M], c[M], d[M], p[M*M], q[M*M];
    bool cmp(int a, int b){return a > b;}
    
    int main(){
        int n, cnt = 0;
        scanf("%d", &n);
        for(int j = 1; j <= n; j++)scanf("%d%d%d%d", &a[j], &b[j], &c[j], &d[j]);
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)p[++cnt] = a[i] + b[j];
        cnt = 0;
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)q[++cnt] = c[i] + d[j];
        sort(p+1, p+1+cnt); sort(q+1, q+1+cnt, cmp);
        p[cnt+1] = q[cnt+1] = inf;
        int st = 1, ed = 1;
        while(st <= cnt || ed <= cnt){
    
            while(p[st] + q[ed] < 0)st++;
            while(p[st] + q[ed] > 0)ed++;
            while(p[st] + q[ed] == 0){
                int cc = st, dd = ed;
                while(p[st] == p[cc])st++;
                while(q[ed] == q[dd])ed++;
                ans += (st - cc) * (ed - dd);
            }
        }
        printf("%d
    ", ans);
    }
    View Code
  • 相关阅读:
    Python学习笔记_从CSV读取数据写入Excel文件中
    Python学习笔记_Python向Excel写入数据
    Python学习笔记_一个Tkinter示例,使用FileDialog
    Python学习笔记_我的参考网址
    Python读取CSV文件,报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xa7 in position 727: illegal multibyte sequence
    Python读取CSV文件
    JS写的多级联select,如何取值
    c#常用的Datable转换为json,以及json转换为DataTable操作方法
    C# 读写App.config
    一个简单的存储过程使用事务的例子
  • 原文地址:https://www.cnblogs.com/EdSheeran/p/9396188.html
Copyright © 2011-2022 走看看