zoukankan      html  css  js  c++  java
  • HDU 4118 Holiday's Accommodation (dfs)

    题意:给n个点,每个点有一个人,有n-1条有权值的边,求所有人不在原来位置所移动的距离的和最大值。

    析:对于每边条,我们可以这么考虑,它的左右两边的点数最少的就是要加的数目,因为最好的情况就是左边到右边,右边到左边,然后用dfs就可以解决了。

    代码如下:

    #pragma comment(linker, "/STACK:1024000000,1024000000")
    #include <cstdio>
    #include <string>
    #include <cstdlib>
    #include <cmath>
    #include <iostream>
    #include <cstring>
    #include <set>
    #include <queue>
    #include <algorithm>
    #include <vector>
    #include <map>
    #include <cctype>
    #include <cmath>
    #include <stack>
    #include <sstream>
    #include <list>
    #define debug() puts("++++");
    #define gcd(a, b) __gcd(a, b)
    #define lson l,m,rt<<1
    #define rson m+1,r,rt<<1|1
    #define freopenr freopen("in.txt", "r", stdin)
    #define freopenw freopen("out.txt", "w", stdout)
    using namespace std;
    
    typedef long long LL;
    typedef unsigned long long ULL;
    typedef pair<int, int> P;
    const int INF = 0x3f3f3f3f;
    const double inf = 0x3f3f3f3f3f3f;
    const double PI = acos(-1.0);
    const double eps = 1e-8;
    const int maxn = 1e5 + 10;
    const int mod = 1000;
    const int dr[] = {-1, 0, 1, 0};
    const int dc[] = {0, 1, 0, -1};
    const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
    int n, m;
    const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    inline bool is_in(int r, int c){
      return r >= 0 && r < n && c >= 0 && c < m;
    }
    
    struct Node{
      int v, val, next;
    };
    Node a[maxn<<1];
    int head[maxn];
    int cnt;
    
    void add(int u, int v, int val){
      a[cnt].v = v;
      a[cnt].val = val;
      a[cnt].next = head[u];
      head[u] = cnt++;
    }
    LL ans;
    int num[maxn];
    void dfs(int u, int fa){
      for(int i = head[u]; ~i; i = a[i].next){
        int v = a[i].v;
        if(v == fa)  continue;
        dfs(v, u);
        num[u] += num[v];
        ans += (LL)a[i].val * min(num[v], n-num[v]);
      }
      ++num[u];
    }
    
    int main(){
      int T;  cin >> T;
      for(int kase = 1; kase <= T; ++kase){
        scanf("%d", &n);
        memset(head, -1, sizeof head);
        cnt = 0;
        for(int i = 1; i < n; ++i){
          int u, v, val;
          scanf("%d %d %d", &u, &v, &val);
          add(u, v, val);
          add(v, u, val);
        }
        ans = 0;
        memset(num, 0, sizeof num);
        dfs(1, -1);
        printf("Case #%d: %I64d
    ", kase, ans*2LL);
      }
      return 0;
    }
    

      

  • 相关阅读:
    JS 日期加多少天,减多少天
    SQL 触发器
    SGU100
    连续子数组的最大和
    字符串的排列
    二叉搜索树与双向链表
    数组中出现次数超过一半的数字
    复杂链表的复制
    二叉树中和为某一值的路径
    二叉搜索树的后序遍历序列
  • 原文地址:https://www.cnblogs.com/dwtfukgv/p/7225797.html
Copyright © 2011-2022 走看看