zoukankan      html  css  js  c++  java
  • [topcoder]TheConsecutiveIntegersDivOne

    http://community.topcoder.com/stat?c=problem_statement&pm=13625&rd=16278

    首先,如果记得曼哈顿距离最小值那个问题,会想起一维的情况可证,点出现在中位数那里是最小的。这里也可证明,四个点,出现在中位数位置是最小的。

    题解里的做法是,试探所有让某个想减的绝对值最小的情况。

    我的代码有点丑,但过了:

    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    class TheConsecutiveIntegersDivOne {
    public:
    	int find(vector <int> numbers, int k) {
    		sort(numbers.begin(), numbers.end());
    		int d = k / 2;
    		int left = 0;
    		int sumL = 0;
    		for (int i = left; i < left + d; i++) {
    			sumL += numbers[i];
    		}
    		int sumR = 0;
    		int right = left + d;
    		if (k % 2 == 1) {
    			right++;
    		}
    		for (int i = right; i < right + d; i++) {
    			sumR += numbers[i];
    		}
    		int result = sumR - sumL - d * d;
    		while (right + d < numbers.size()) {
    			sumL += numbers[left + d];
    			sumL -= numbers[left];
    			sumR += numbers[right + d];
    			sumR -= numbers[right];
    			result = min(result, sumR - sumL - d * d);
    			left++;
    			right++;
    		}
    		return result;
    	}
    };
    

      

  • 相关阅读:
    工作中的几个问题
    linux初学之二
    VMWARE虚拟机卡死
    记昨天、今天的部分工作内容及问题
    linux初学之一
    今日阅读项目源码
    python POST XML
    python的超简单WEB服务器
    在notepad++中运行python
    安装python图形库:Matplotlib
  • 原文地址:https://www.cnblogs.com/lautsie/p/4242975.html
Copyright © 2011-2022 走看看