例题 8-3 UVA - 1152 4 Values whose Sum is 0(和为0的4个值)(二分枚举)
2016-05-19 14:58
489 查看
题意:
给你4个n 元素的集合ABCD,要求分别从中选取一个元素abcd使得a + b + c + d = 0问有多少种选法!
思路:
先把A数组和B数组所有的组合情况都记录到tmp数组,排序,然后枚举C数组和D数组,取相反数,然后二分枚举tmp数组中值,
取上界upper_bound 和取下界 lower_bound 做差即可!
给你4个n 元素的集合ABCD,要求分别从中选取一个元素abcd使得a + b + c + d = 0问有多少种选法!
思路:
先把A数组和B数组所有的组合情况都记录到tmp数组,排序,然后枚举C数组和D数组,取相反数,然后二分枚举tmp数组中值,
取上界upper_bound 和取下界 lower_bound 做差即可!
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 5000 + 5; int a[maxn],b[maxn],c[maxn],d[maxn]; int tmp[maxn*maxn]; int main(){ int T,cnt2 = 0; scanf("%d",&T); while(T--){ int n,cnt=0; scanf("%d",&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) tmp[cnt++] = a[i] + b[j]; sort(tmp,tmp+cnt); int ans = 0; for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ int k = -c[i]-d[j]; int pos1 = upper_bound(tmp,tmp+cnt,k) - tmp; int pos2 = lower_bound(tmp,tmp+cnt,k) - tmp; ans += pos1-pos2; } } if (cnt2++)printf("\n"); printf("%d\n",ans); } return 0; }
相关文章推荐
- 优化UITableViewCell高度计算的那些事
- Fiddler(七) | QuickExec
- 23.UIView
- jqyery easyui $.messager.alert 位置代码
- UGUI-界面多分辨率适配
- web动画的方式 aa3e requestAnimationFrame
- maven build脚本笔记
- 关于iOS中的弹出窗口----UIAlertController
- UUID
- 解决ADT大量出现"Unexpected value from nativeGetEnabledTags: 0"的问提
- iOS学习之——UIButton
- 使用Hibernate SQLQuery执行原生SQL
- Quickly Search Articles in My Blog - 快速搜索本专栏内的文章
- UIColor+Hex
- UITableView的属性和方法
- easyui datagrid使用updateRow更改单元格值后getChanges无法获取
- UISegmentedControl 功能简单 分析
- Android Studio 解决 finished with non zero exit value
- UILabel指定区域变颜色,UILabel指定数字变颜色
- STL之priority_queue(优先队列)