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
  • 相关阅读:
    数据库中的 索引
    JQuery中ajax请求
    如何优化广告,提高点击率
    常用的正则表达式
    全栈工程师之路中级篇之小程序开发前言
    ionic入门教程第四课使用$controllerProvider按需加载controller
    全栈工程师之路中级篇之小程序开发第一章第一节注册小程序
    ionic入门教程第三课在项目中使用requirejs分离controller文件和server文件
    ionic入门教程第五课举例子说明异步回调$q及$q在项目中的用法
    求两个整数的最大公约数和最小公倍数
  • 原文地址:https://www.cnblogs.com/EdSheeran/p/9396188.html
Copyright © 2011-2022 走看看