HDOJ-2578-Dating with girls(1) 【排序 去重 二分】
2015-11-01 18:04
453 查看
Dating with girls(1)
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4042 Accepted Submission(s): 1248
[align=left]Problem Description[/align]
Everyone in the HDU knows that the number of boys is larger than the number of girls. But now, every boy wants to date with pretty girls. The girls like to date with the boys with higher IQ. In order to test the boys ' IQ, The girls
make a problem, and the boys who can solve the problem
correctly and cost less time can date with them.
The problem is that : give you n positive integers and an integer k. You need to calculate how many different solutions the equation x + y = k has . x and y must be among the given n integers. Two solutions are different if x0 != x1 or y0 != y1.
Now smart Acmers, solving the problem as soon as possible. So you can dating with pretty girls. How wonderful!
[align=left]Input[/align]
The first line contain an integer T. Then T cases followed. Each case begins with two integers n(2 <= n <= 100000) , k(0 <= k < 2^31). And then the next line contain n integers.
[align=left]Output[/align]
For each cases,output the numbers of solutions to the equation.
[align=left]Sample Input[/align]
2 5 4 1 2 3 4 5 8 8 1 4 5 7 8 9 2 6
[align=left]Sample Output[/align]
3 5
恩,题目大意就是说,给 n 个数和 k ,然后从这 n 个数中找两个数相加和为 k ,问共有多少种组合,例如 3 + 2 = 5 和 2 + 3 = 5 为两种,但 4 + 4 = 8 就一种。开始直接 for 循环写,结果超时,看讨论区,要去重,还是会超时,所以要二分查找。
#include <iostream> #include<cstdio> #include<cstring> #define maxn 100000+10 #include<algorithm> using namespace std; int rec[maxn]; int n; int bsearch(int s) { int l=0,r=n-1,mid; while(l<=r) { mid=(l+r)>>1; if(rec[mid]==s) return 1; if(s<rec[mid]) r=mid-1; else l=mid+1; } return 0; } int main() { int t,k,cnt,flag; scanf("%d",&t); while(t--) { flag=cnt=0; scanf("%d%d",&n,&k); for(int i=0;i<n;++i) scanf("%d",&rec[i]); sort(rec,rec+n); rec =-1; for(int i=0;i<n;++i) { if(rec[i]!=rec[i+1]&&bsearch(k-rec[i])) { cnt++; } } printf("%d\n",cnt); } return 0; }
相关文章推荐
- filter和interceptor的区别
- 程序中的@Override是什么意思?
- spring mvc常用的注解
- oracle中的分支与循环语句
- お手紙のこと。
- UVa 10114 - Loansome Car Buyer
- [leetcode 26]Remove Duplicates from Sorted Array
- JDK所有版本下载链接
- 跨域rest-service创建与访问解决方案
- request.setCharacterEncoding("UTF-8");
- HDOJ1728(限制转弯的迷宫问题)
- CSS3之2D变形
- Fragment介绍:
- Fragment源码阅读笔记
- C- 流程控制(顺序结构,选择结构,循环结构)
- 黑马程序员_正则表达式的一些总结
- [leetcode 107]Binary Tree Level Order Traversal II
- CSS reset的重新审视 – 避免样式重置
- G - Antiarithmetic?
- 跨界技术人