zoukankan      html  css  js  c++  java
  • uva-10487-枚举

    题意:给你一个集合,每俩个数相加得到一个和s,输入s1,问离s1最近的s是多少

    二分,注意如果二分出相等,那一定是最近的数,要不然就比较最后mid和mid-1的数

     
    #include <string>
    #include<iostream>
    #include<map>
    #include<memory.h>
    #include<vector>
    #include<algorithm>
    #include<queue>
    #include<vector>
    
    
    namespace cc
    {
    	using std::cout;
    	using std::endl;
    	using std::cin;
    	using std::map;
    	using std::vector;
    	using std::string;
    	using std::sort;
    	using std::priority_queue;
    	using std::greater;
    	using std::vector;
    	using std::swap;
    
    	constexpr int N = 1001;
    	//constexpr int N = 30;
    
    	//priority_queue<int,vector<int>, greater<int> >q;
    
    	int a[N];
    	int b[N*N];
    
    	void solve()
    	{
    
    		int n;
    		int t = 0;
    		while (cin >> n && n)
    		{
    			t++;
    			for (int i = 0;i < n;++i)
    				cin >> a[i];
    			int k = 0;
    			for (int i = 0;i < n - 1;i++)
    			{
    				for (int j = i + 1;j < n;j++)
    				{
    					b[k++] = a[i] + a[j];
    				}
    			}
    			sort(b, b + k);
    			int c, q;
    			cin >> c;
    			cout << "Case " << t << ":" << endl;
    			while (c)
    			{
    				cin >> q;
    				int qq = INT32_MAX;
    				int l = 0, r = k-1;
    				int mid=0;
    				int ok = 0;
    				while (l <= r)
    				{
    					mid = (l + r) / 2;
    					if (b[mid] < q)
    						l = mid + 1;
    					else if (b[mid] > q)
    						r = r - 1;
    					else
    					{
    						ok = 1;
    						break;
    					}
    				}
    				if(ok)
    				cout << "Closest sum to " << q << " is " << q<<"." << endl;
    				else
    				{
    					if(mid==0)
    						cout << "Closest sum to " << q << " is " << b[mid] << "." << endl;
    					else if(abs(b[mid-1]-q) < abs(b[mid]-q))
    						cout << "Closest sum to " << q << " is " << b[mid-1] << "." << endl;
    					else
    						cout << "Closest sum to " << q << " is " << b[mid] << "." << endl;
    				}
    				--c;
    			}
    		}
    
    	}
    
    };
    
    
    int main()
    {
    
    #ifndef ONLINE_JUDGE
    	freopen("d://1.text", "r", stdin);
    #endif // !ONLINE_JUDGE
    	cc::solve();
    
    	return 0;
    }
    

      

  • 相关阅读:
    leetCode 78.Subsets (子集) 解题思路和方法
    大话设计模式C++版——代理模式
    不用加减乘除做加法
    hdu 1257
    小学生算术
    字符串排序问题
    POJ 2421 Constructing Roads
    http://vdceye.com/ 全新页面上线
    POJ3262 Protecting the Flowers 【贪心】
    集群环境下JSP中获取客户端IP地址的方法
  • 原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/9949697.html
Copyright © 2011-2022 走看看