zoukankan      html  css  js  c++  java
  • ACM zb的生日

    zb的生日

    时间限制:3000 ms  |  内存限制:65535 KB
    难度:2
     
    描述
    今天是阴历七月初五,acm队员zb的生日。zb正在和C小加、never在武汉集训。他想给这两位兄弟买点什么庆祝生日,经过调查,zb发现C小加和never都很喜欢吃西瓜,而且一吃就是一堆的那种,zb立刻下定决心买了一堆西瓜。当他准备把西瓜送给C小加和never的时候,遇到了一个难题,never和C小加不在一块住,只能把西瓜分成两堆给他们,为了对每个人都公平,他想让两堆的重量之差最小。每个西瓜的重量已知,你能帮帮他么?
     
    输入
    多组测试数据(<=1500)。数据以EOF结尾
    第一行输入西瓜数量N (1 ≤ N ≤ 20)
    第二行有N个数,W1, …, Wn (1 ≤ Wi ≤ 10000)分别代表每个西瓜的重量
    输出
    输出分成两堆后的质量差
    样例输入
    5
    5 8 13 27 14
    样例输出
    3
    本题的用暴力搜索,想好解答树,一边搜索一边剪枝
    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <cmath>
    #include <numeric>
    using namespace std;
    
    int ans = 0;
    int sumWeight = 0;
    
    void dfs(int index,int v, vector<int>& weight){
        if (index == weight.size()) return ;
        ans = min(ans,abs(sumWeight-2*v));
        dfs(index+1,v,weight);
        dfs(index+1,v+weight[index],weight);
    }
    
    int main(){
        int n;
        while(cin >> n){
            vector<int> weight(n);
            for(int i = 0; i < n ; ++ i) cin >> weight[i];
            sumWeight = accumulate(weight.begin(),weight.end(),0);
            ans = sumWeight;
            dfs(0,0,weight);
            cout<<ans<<endl;
        }
    }
     
  • 相关阅读:
    跳出iframe
    leetcode 225. Implement Stack using Queues
    leetcode 206. Reverse Linked List
    leetcode 205. Isomorphic Strings
    leetcode 203. Remove Linked List Elements
    leetcode 198. House Robber
    leetcode 190. Reverse Bits
    leetcode leetcode 783. Minimum Distance Between BST Nodes
    leetcode 202. Happy Number
    leetcode 389. Find the Difference
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3702883.html
Copyright © 2011-2022 走看看