hdu 2578 Dating with girls(1) 满足条件x+y=k的x,y有几组
Dating with girls(1)
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5709 Accepted Submission(s): 1855
Problem Description
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!
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!
Input
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.
Output
For each cases,output the numbers of solutions to the equation.
Sample Input
2
5 4
1 2 3 4 5
8 8
1 4 5 7 8 9 2 6
Sample Output
3
5
题意:在给定的 n 个数中,满足x + y = k 的x,y有几组(1,3和3,1被认为是不同的两组)
题解:
1、二分:用二分在数组a[i]中查找,判断k-a[i]是否存在,若a[i]>k或 a[i]==a[i-1] (重复),就continue;否则存在就cnt++
2、map标记,一开始我是想到开一个vis数组标记,但是考虑到数据范围太大,就放弃了。
1、二分
#include<iostream> #include<algorithm> #include<math.h> #define ll long long using namespace std; ll a[100005]; int find1(ll target, ll l,ll r)//l,r是查找的左右区间 { ll left = l, right = r, mid; while (left <= right) { mid = left + (right - left) / 2; if (a[mid] == target) return mid; else if (a[mid] > target) right = mid - 1; else left = mid + 1; } return -1; } int main() { ll t,n,k,cnt; scanf("%lld",&t); while(t--) { cnt=0; scanf("%lld%lld",&n,&k); for(int i=0;i<n;i++) scanf("%lld",&a[i]); sort(a,a+n); for(int i=0;i<n;i++) { if(a[i]>k||a[i]==a[i-1]) continue; else { if(find1(k-a[i],0,n)!=-1) cnt++; } } printf("%lld\n",cnt); } }
2、map
#include<iostream> #include<map> #define ll long long using namespace std; map<ll,ll>m; ll a[100005]; int main() { ll t,n,k,cnt; scanf("%lld",&t); while(t--) { m.clear(),cnt=0; scanf("%lld%lld",&n,&k); for(int i=0;i<n;i++) { scanf("%lld",&a[i]); if(!m[a[i]]) m[a[i]]=1; else { i--;//删除重复的数 n--; } } for(int i=0;i<n;i++) { if(a[i]>k) continue; if(m[k-a[i]]==1) cnt++; } printf("%lld\n",cnt); } return 0; }
等风起的那一天,我已准备好一切