二分贪心d
来源:互联网 发布:关键词分分析软件 编辑:程序博客网 时间:2024/05/20 05:08
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 -4626 -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).
这个题需要用二分,如果不用二分的话会超时,先求出所有a+b的值,然后用每个c+d的值二分查找a+b的值。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int x,l,r,m,k;
int main()
{
vector<int>f;
int e;
cin>>e;
int a[4005],b[4005],c[4005],d[4005],x1=0,i,j,y=0;
for(i=0;i<e;i++)
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
for(i=0;i<e;i++)
{
for(j=0;j<e;j++)
{
f.push_back(a[i]+b[j]);
x1++;
}
}
sort(f.begin(),f.end());
for(i=0;i<e;i++)
{
for(j=0;j<e;j++)
{
//cout<<y<<endl;
x=-c[i]-d[j];
l=0;
r=x1-1;
while(l<=r)
{
//cout<<y<<endl;
m=(l+r)/2;
if(f[m]>x)
r=m-1;
else
if(f[m]<x)
l=m+1;
else
{
for(k=m;k>=0;k--)
{
if(f[k]==x)
y++;
else
break;
}
for(k=m+1;k<x1;k++)
{
if(f[k]==x)
y++;
else
break;
}
break;
}
}
}
}
cout<<y;
}
#include<vector>
#include<algorithm>
using namespace std;
int x,l,r,m,k;
int main()
{
vector<int>f;
int e;
cin>>e;
int a[4005],b[4005],c[4005],d[4005],x1=0,i,j,y=0;
for(i=0;i<e;i++)
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
for(i=0;i<e;i++)
{
for(j=0;j<e;j++)
{
f.push_back(a[i]+b[j]);
x1++;
}
}
sort(f.begin(),f.end());
for(i=0;i<e;i++)
{
for(j=0;j<e;j++)
{
//cout<<y<<endl;
x=-c[i]-d[j];
l=0;
r=x1-1;
while(l<=r)
{
//cout<<y<<endl;
m=(l+r)/2;
if(f[m]>x)
r=m-1;
else
if(f[m]<x)
l=m+1;
else
{
for(k=m;k>=0;k--)
{
if(f[k]==x)
y++;
else
break;
}
for(k=m+1;k<x1;k++)
{
if(f[k]==x)
y++;
else
break;
}
break;
}
}
}
}
cout<<y;
}
0 0
- 二分贪心专题D
- 二分贪心 D
- 二分贪心 D
- 二分贪心 D题
- 二分贪心—D
- 二分贪心-D
- 二分贪心d
- 二分贪心-D
- CFcontest377-D 贪心,二分
- Codeforces 609D 贪心+二分
- codeforces 732D (二分 贪心)
- 【codeforces 732D】【二分+贪心】
- Codeforces #732D 二分 贪心
- CodeForces 363D 【二分+贪心】
- Atcoder 056 D 贪心+二分
- ACM-二分贪心D-04
- 二分贪心练习题D-4
- CodeForces 614D 二分+贪心
- js中this的指向
- 在 Ubuntu 14.x 搭建 Nginx Uwsgi Django 环境之(三):连接 nginx 和 uwsgi
- 链表类面试题
- Git远端仓库被不同版本的本地仓库push,不能正常提交代码
- HDU 1020 Encoding
- 二分贪心d
- opencv3.2生成不依赖vs2015的dll
- 霍夫曼编码的实现(数组模拟)
- Android之Activity的四种启动模式
- cookie,sessionStorage,localStorage分别是什么,以及三者之间的区别
- AVL树的旋转LL RR LR RL
- ES6的let和const命令(一)
- Java容器_4个接口
- 【学习笔记】java面向对象复习04