POJ 2785 4 Values whose Sum is 0

sort+二分(求上下界):qsort + 纯二分 会TE:

sort用法:

头文件:
#include <algorithm>
using namespace std;

1.默认的sort函数是按升序排。对应于1)
sort(a,a+n);   //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。对应于2)
例如:
int cmp( const int &a, const int &b ){
    if( a > b )
       return 1;
    else
       return 0;
}
sort(a,a+n,cmp);
是对数组a降序排序
又如:
int cmp( const POINT &a, const POINT &b ){
    if( a.x < b.x )
       return 1;
    else
       if( a.x == b.x ){
          if( a.y < b.y )
             return 1;
          else
             return 0;
        }
       else
          return 0;
}
sort(a,a+n,cmp);
是先按x升序排序,若x值相等则按y升序排

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#define MAXN 4010

using namespace std;

long long int num;
int n, t2;
int a[MAXN], b[MAXN], c[MAXN], d[MAXN],f1[MAXN*MAXN],f2[MAXN*MAXN];
int cmp(const void *_p, const void *_q)
{
return *((int *)_p) - *((int *)_q);
}
int lower_bd(int* f, int t, int v)
{
/*
int max, mid, min;
min = 0;
max = t;
for(;;)
{
mid = (min + max) / 2;
if(mid == min)
break;
if(f[mid] < v)
min = mid;
else
max = mid;
}
return f[mid] >= v ? mid : mid + 1;
*/
int m;
int first = 0;
while(first < t)
{
m = first + (t - first)/2;
if(f[m] >= v) t = m;
else first = m+1;
}
return first;
}
int up_bd(int* f,int t, int v)
{
/*int max, min, mid;
max = t;
min = 0;
for(;;)
{
mid = (max + min) / 2;
if(mid == min)
break;
if(f[mid] <= v)
min = mid;
else
max = mid;
}
return f[mid] > v ? mid : mid + 1;
*/
int m;
int first = 0;
while(first < t)
{
m = first + (t - first)/2;
if(f[m] <= v) first = m + 1;
else t = m;
}
return first;
}
void input()
{
int p, ch, i, j, max, min;
while(scanf("%d",&n) == 1)
{
for(i = 0; i < n; i ++)
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
t2 = 0;
for(i = 0; i < n; i ++)
for(j = 0; j < n; j ++)
{
f1[t2] = a[i] + b[j];
f2[t2] = c[i] + d[j];
++ t2;
}
sort(f1, f1 + t2);
sort(f2, f2 + t2);
//qsort(f1,t2,sizeof(f1[0]),cmp);
// qsort(f2,t2,sizeof(f2[0]),cmp);
//for(int i = 0; i < t1; i ++)
// printf("i=%d f1[i]=%d f2[i]=%d\n",i,f1[i],f2[i]);
num = 0;
p = -1;
for(i = 0; i < t2; i ++)
{
if(f1[i] == p)
num += ch;
else
{
max = up_bd(f2,t2,-f1[i]);
min = lower_bd(f2,t2,-f1[i]);
ch = max - min;
num += ch;
}
p = f1[i];
}
printf("%lld\n",num);
}
}
int main()
{
input();
return 0;
}



你可能感兴趣的:(value)