标签:ace number return stdio.h scan rup nbsp ret poj2785
传送门:http://poj.org/problem?id=2785
Description
Input
Output
Sample Input
6 -45 22 42 -16 -41 -27 56 30 -36 53 -37 77 -36 30 -75 -46 26 -38 -10 62 -32 -54 -6 45
Sample Output
5
Hint
给你一个数字n,然后有n组每组4个数,求每一列取出一个数,使最终四个数的和为0,求有多少种组合方式
解题思路:先求出来前两列和后两列的和,然后二分就可以了,对于这道题来说结果没有去重
1 #include<vector> 2 #include<set> 3 #include<stdio.h> 4 #include<algorithm> 5 using namespace std; 6 7 vector <int > a; 8 vector <int > b; 9 vector <int > c; 10 vector <int > d; 11 vector <int > sum1; 12 vector <int > sum2; 13 int main() 14 { 15 int n, i, j, a1, b1, c1, d1, sum; 16 while(scanf("%d", &n)!=EOF) { 17 sum = 0; 18 for(i = 0; i < n; i++) 19 { 20 scanf("%d%d%d%d", &a1, &b1, &c1, &d1); 21 a.push_back(a1); 22 b.push_back(b1); 23 c.push_back(c1); 24 d.push_back(d1); 25 } 26 for(i = 0; i < n; i++) { 27 for(j = 0; j < n; j++) { 28 sum1.push_back(a[i] + b[j]); 29 sum2.push_back(c[i] + d[j]); 30 } 31 } 32 33 /* for(i = 0; i < sum1.size(); i++) { 34 for(j = 0; j < sum2.size(); j++) { 35 if(sum1[i]+sum2[j] == 0) { 36 sum++; 37 } 38 } 39 }*/ 40 n = sum2.size(); 41 sort(sum2.begin(),sum2.end()); 42 43 for(i = 0; i < n; i++) { 44 int l = 0, r = n-1, mid; 45 while(l <= r) { 46 mid = (l + r) / 2; 47 if(sum1[i] + sum2[mid] == 0) { 48 sum++; 49 for(j = mid + 1; j < n; j++) { 50 if(sum1[i] + sum2[j] != 0) 51 break; 52 else 53 sum++; 54 } 55 for(j = mid - 1; j >= 0; j--) { 56 if(sum1[i] + sum2[j] != 0) 57 break; 58 else 59 sum++; 60 } 61 break; 62 } 63 if(sum1[i] + sum2[mid] < 0) 64 l = mid + 1; 65 else 66 r = mid - 1; 67 } 68 } 69 printf("%d\n", sum); 70 } 71 return 0; 72 }
POJ2785-4 Values whose Sum is 0
标签:ace number return stdio.h scan rup nbsp ret poj2785
原文地址:http://www.cnblogs.com/ljmzzyk/p/7271894.html