题目链接 http://acm.hust.edu.cn/vjudge/problem/21350
解题思路
先排序。
对于每个数,找到另外两个数,使得与其中一个加起来小于目标与另外一个加起来大于目标。
如果找不到可能是只能选头两个或末尾两个。
再求绝对值那个更小就行了。
代码
#include<stdio.h> #include<algorithm> #define MAX_NUM 1<<31-1 using namespace std; const int maxLen = 1005; int data[maxLen]; int targer[26]; int ans[26]; int minv; int Judge(int i, int n, int t) { int pre = -1; for(int k=i+1; k<n-1; k++) if(data[k]+data[i]<t && data[k+1]+data[i]>=t) pre=k; if(pre==-1) { if(data[i]+data[n-1]<t) { if(abs(data[i]+data[n-1]-t)<minv) { minv = abs(data[i]+data[n-1]-t); return data[i]+data[n-1]; } else return MAX_NUM; } else if(data[i]+data[i+1]>=t) { if(abs(data[i]+data[i+1]-t)<minv) { minv = abs(data[i]+data[i+1]-t); return data[i]+data[i+1]; } else return MAX_NUM; } } else if(abs(data[i]+data[pre]-t)<abs(data[i]+data[pre+1]-t)) { if(minv>abs(data[i]+data[pre]-t)) { minv = abs(data[i]+data[pre]-t); return data[i]+data[pre]; } else return MAX_NUM; } else if(minv>abs(data[i]+data[pre+1]-t)) { minv = abs(data[i]+data[pre+1]-t); return data[i]+data[pre+1]; } else return MAX_NUM; } int main() { int n, cases = 1; scanf("%d", &n); while(n != 0) { for(int i=0; i<n; i++) scanf("%d", &data[i]); sort(data, data+n); int m; scanf("%d", &m); for(int i=0; i<m; i++) { scanf("%d", &targer[i]); minv = MAX_NUM; for(int j=0; j<n-1; j++) { int a = Judge(j,n,targer[i]); if(a != MAX_NUM) ans[i] = a; } } printf("Case %d:\n", cases); for(int i=0; i<m; i++) printf("Closest sum to %d is %d.\n", targer[i], ans[i]); cases++; scanf("%d", &n); } return 0; }
时间: 2024-09-29 02:38:10