結果

問題 No.1124 Earthquake Safety
ユーザー kkishikkishi
提出日時 2021-01-09 11:12:44
言語 C++17(clang)
(17.0.6 + boost 1.83.0)
結果
AC  
実行時間 754 ms / 3,000 ms
コード長 14,436 bytes
コンパイル時間 3,662 ms
コンパイル使用メモリ 174,976 KB
実行使用メモリ 137,316 KB
最終ジャッジ日時 2024-11-17 13:25:41
合計ジャッジ時間 34,121 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 1 ms
5,248 KB
testcase_02 AC 2 ms
5,248 KB
testcase_03 AC 2 ms
5,248 KB
testcase_04 AC 1 ms
5,248 KB
testcase_05 AC 2 ms
5,248 KB
testcase_06 AC 2 ms
5,248 KB
testcase_07 AC 12 ms
6,784 KB
testcase_08 AC 189 ms
39,552 KB
testcase_09 AC 665 ms
112,384 KB
testcase_10 AC 270 ms
113,392 KB
testcase_11 AC 2 ms
5,248 KB
testcase_12 AC 1 ms
5,248 KB
testcase_13 AC 1 ms
5,248 KB
testcase_14 AC 753 ms
112,212 KB
testcase_15 AC 730 ms
112,240 KB
testcase_16 AC 746 ms
112,256 KB
testcase_17 AC 754 ms
112,232 KB
testcase_18 AC 721 ms
112,236 KB
testcase_19 AC 709 ms
112,252 KB
testcase_20 AC 738 ms
112,128 KB
testcase_21 AC 741 ms
112,328 KB
testcase_22 AC 730 ms
112,240 KB
testcase_23 AC 729 ms
111,280 KB
testcase_24 AC 725 ms
111,472 KB
testcase_25 AC 713 ms
111,488 KB
testcase_26 AC 693 ms
111,456 KB
testcase_27 AC 699 ms
111,740 KB
testcase_28 AC 710 ms
111,848 KB
testcase_29 AC 725 ms
112,768 KB
testcase_30 AC 743 ms
112,768 KB
testcase_31 AC 739 ms
112,264 KB
testcase_32 AC 743 ms
113,712 KB
testcase_33 AC 731 ms
110,296 KB
testcase_34 AC 744 ms
109,476 KB
testcase_35 AC 697 ms
113,892 KB
testcase_36 AC 667 ms
111,684 KB
testcase_37 AC 681 ms
115,932 KB
testcase_38 AC 652 ms
114,432 KB
testcase_39 AC 610 ms
112,824 KB
testcase_40 AC 612 ms
115,448 KB
testcase_41 AC 599 ms
113,268 KB
testcase_42 AC 565 ms
114,660 KB
testcase_43 AC 566 ms
115,712 KB
testcase_44 AC 560 ms
115,256 KB
testcase_45 AC 540 ms
113,892 KB
testcase_46 AC 614 ms
114,928 KB
testcase_47 AC 607 ms
114,048 KB
testcase_48 AC 505 ms
116,468 KB
testcase_49 AC 454 ms
137,316 KB
testcase_50 AC 1 ms
5,248 KB
testcase_51 AC 2 ms
5,248 KB
testcase_52 AC 1 ms
5,248 KB
testcase_53 AC 1 ms
5,248 KB
testcase_54 AC 2 ms
5,248 KB
testcase_55 AC 1 ms
5,248 KB
testcase_56 AC 1 ms
5,248 KB
testcase_57 AC 1 ms
5,248 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp:225:9: warning: #pragma once in main file [-Wpragma-once-outside-header]
  225 | #pragma once
      |         ^
1 warning generated.

ソースコード

diff #

#include <bits/stdc++.h>

#include <boost/hana/functional/fix.hpp>

template <typename T, typename = void>
struct is_dereferenceable : std::false_type {};
template <typename T>
struct is_dereferenceable<T, std::void_t<decltype(*std::declval<T>())>>
    : std::true_type {};

template <typename T, typename = void>
struct is_iterable : std::false_type {};
template <typename T>
struct is_iterable<T, std::void_t<decltype(std::begin(std::declval<T>())),
                                  decltype(std::end(std::declval<T>()))>>
    : std::true_type {};

template <typename T, typename = void>
struct is_applicable : std::false_type {};
template <typename T>
struct is_applicable<T, std::void_t<decltype(std::tuple_size<T>::value)>>
    : std::true_type {};

template <typename T, typename... Ts>
void debug(const T& value, const Ts&... args);
template <typename T>
void debug(const T& v) {
  if constexpr (is_dereferenceable<T>::value) {
    std::cerr << "{";
    if (v) {
      debug(*v);
    } else {
      std::cerr << "nil";
    }
    std::cerr << "}";
  } else if constexpr (is_iterable<T>::value &&
                       !std::is_same<T, std::string>::value) {
    std::cerr << "{";
    for (auto it = std::begin(v); it != std::end(v); ++it) {
      if (it != std::begin(v)) std::cerr << ", ";
      debug(*it);
    }
    std::cerr << "}";
  } else if constexpr (is_applicable<T>::value) {
    std::cerr << "{";
    std::apply([](const auto&... args) { debug(args...); }, v);
    std::cerr << "}";
  } else {
    std::cerr << v;
  }
}
template <typename T, typename... Ts>
void debug(const T& value, const Ts&... args) {
  debug(value);
  std::cerr << ", ";
  debug(args...);
}
#if DEBUG
#define dbg(...)                        \
  do {                                  \
    cerr << #__VA_ARGS__ << ": ";       \
    debug(__VA_ARGS__);                 \
    cerr << " (L" << __LINE__ << ")\n"; \
  } while (0)
#else
#define dbg(...)
#endif

void read_from_cin() {}
template <typename T, typename... Ts>
void read_from_cin(T& value, Ts&... args) {
  std::cin >> value;
  read_from_cin(args...);
}
#define rd(type, ...) \
  type __VA_ARGS__;   \
  read_from_cin(__VA_ARGS__);
#define ints(...) rd(int, __VA_ARGS__);
#define strings(...) rd(string, __VA_ARGS__);

template <typename T>
void write_to_cout(const T& value) {
  if constexpr (std::is_same<T, bool>::value) {
    std::cout << (value ? "Yes" : "No");
  } else {
    std::cout << value;
  }
}
template <typename T, typename... Ts>
void write_to_cout(const T& value, const Ts&... args) {
  write_to_cout(value);
  std::cout << ' ';
  write_to_cout(args...);
}
#define wt(...)                 \
  do {                          \
    write_to_cout(__VA_ARGS__); \
    cout << '\n';               \
  } while (0)

#define all(x) (x).begin(), (x).end()
#define eb(...) emplace_back(__VA_ARGS__)
#define pb(...) push_back(__VA_ARGS__)

#define dispatch(_1, _2, _3, name, ...) name

#define as_i64(x)                                                          \
  (                                                                        \
      [] {                                                                 \
        static_assert(                                                     \
            std::is_integral<                                              \
                typename std::remove_reference<decltype(x)>::type>::value, \
            "rep macro supports std integral types only");                 \
      },                                                                   \
      static_cast<std::int64_t>(x))

#define rep3(i, a, b) for (std::int64_t i = as_i64(a); i < as_i64(b); ++i)
#define rep2(i, n) rep3(i, 0, n)
#define rep1(n) rep2(_loop_variable_, n)
#define rep(...) dispatch(__VA_ARGS__, rep3, rep2, rep1)(__VA_ARGS__)

#define rrep3(i, a, b) for (std::int64_t i = as_i64(b) - 1; i >= as_i64(a); --i)
#define rrep2(i, n) rrep3(i, 0, n)
#define rrep1(n) rrep2(_loop_variable_, n)
#define rrep(...) dispatch(__VA_ARGS__, rrep3, rrep2, rrep1)(__VA_ARGS__)

#define each3(k, v, c) for (auto&& [k, v] : c)
#define each2(e, c) for (auto&& e : c)
#define each(...) dispatch(__VA_ARGS__, each3, each2)(__VA_ARGS__)

template <typename T>
std::istream& operator>>(std::istream& is, std::vector<T>& v) {
  for (T& vi : v) is >> vi;
  return is;
}

template <typename T, typename U>
std::istream& operator>>(std::istream& is, std::pair<T, U>& p) {
  is >> p.first >> p.second;
  return is;
}

template <typename T, typename U>
bool chmax(T& a, U b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}

template <typename T, typename U>
bool chmin(T& a, U b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}

template <typename T, typename U>
auto max(T a, U b) {
  return a > b ? a : b;
}

template <typename T, typename U>
auto min(T a, U b) {
  return a < b ? a : b;
}

template <typename T>
int sz(const T& v) {
  return v.size();
}

template <typename T>
int popcount(T i) {
  return std::bitset<std::numeric_limits<T>::digits>(i).count();
}

template <typename T>
bool hasbit(T s, int i) {
  return std::bitset<std::numeric_limits<T>::digits>(s)[i];
}

template <typename T, typename U>
auto div_ceil(T n, U d) {
  return (n + d - 1) / d;
}

template <typename T>
bool even(T x) {
  return x % 2 == 0;
}

const std::int64_t big = std::numeric_limits<std::int64_t>::max() / 10;

using i64 = std::int64_t;
using i32 = std::int32_t;

template <typename T>
using low_priority_queue =
    std::priority_queue<T, std::vector<T>, std::greater<T>>;

template <typename T>
using V = std::vector<T>;
template <typename T>
using VV = V<V<T>>;

void Main();

int main() {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(NULL);
  std::cout << std::fixed << std::setprecision(20);
  Main();
  return 0;
}

const auto& Fix = boost::hana::fix;

using namespace std;

#define int i64
#pragma once

template <typename T>
class BidirectedGraph {
 public:
  struct Edge {
    int from, to;
    T weight;
    Edge* back = nullptr;
    Edge(int from, int to, T weight = T())
        : from(from), to(to), weight(weight) {}
  };

  BidirectedGraph(int n) : edges_(n) {}
  std::pair<Edge&, Edge&> AddEdge(int from, int to, T weight = T()) {
    Edge& forward = AddDirectedEdge(from, to, weight);
    Edge& back = AddDirectedEdge(to, from, weight);
    forward.back = &back;
    back.back = &forward;
    return {forward, back};
  }
  const std::vector<std::unique_ptr<Edge>>& Edges(int from) const {
    return edges_[from];
  }
  std::vector<std::unique_ptr<Edge>>& MutableEdges(int from) {
    return edges_[from];
  }
  int NumVertices() const { return edges_.size(); }

 private:
  Edge& AddDirectedEdge(int from, int to, T weight = T()) {
    edges_[from].push_back(std::make_unique<Edge>(from, to, weight));
    return *edges_[from].back();
  }

  std::vector<std::vector<std::unique_ptr<Edge>>> edges_;
};

#define BIN_OPS(F) F(+) F(-) F(*) F(/)
#define CMP_OPS(F) F(!=) F(<) F(<=) F(==) F(>) F(>=)

template <int Mod = 1000000007>
class ModInt {
 public:
  ModInt() : n_(0) {}
  ModInt(long long n) : n_(n % Mod) {
    if (n_ < 0) {
      // In C++, (-n)%m == -(n%m).
      n_ += Mod;
    }
  }
  ModInt& operator+=(const ModInt& m) {
    n_ += m.n_;
    if (n_ >= Mod) {
      n_ -= Mod;
    }
    return *this;
  }
  ModInt& operator++() { return (*this) += 1; }
  ModInt& operator-=(const ModInt& m) {
    n_ -= m.n_;
    if (n_ < 0) {
      n_ += Mod;
    }
    return *this;
  }
  ModInt& operator--() { return (*this) -= 1; }
  ModInt& operator*=(const ModInt& m) {
    n_ *= m.n_;
    n_ %= Mod;
    return *this;
  }
  ModInt& operator/=(const ModInt& m) {
    *this *= m.Inv();
    return *this;
  }
#define DEFINE(op) \
  ModInt operator op(const ModInt& m) const { return ModInt(*this) op## = m; }
  BIN_OPS(DEFINE)
#undef DEFINE
#define DEFINE(op) \
  bool operator op(const ModInt& m) const { return n_ op m.n_; }
  CMP_OPS(DEFINE)
#undef DEFINE
  ModInt operator-() const { return ModInt(-n_); }
  ModInt Pow(int n) const {
    if (n < 0) {
      return Inv().Pow(-n);
    }
    // a * b ^ n = answer.
    ModInt a = 1, b = *this;
    while (n != 0) {
      if (n & 1) {
        a *= b;
      }
      n /= 2;
      b *= b;
    }
    return a;
  }
  ModInt Inv() const {
    // Compute the inverse based on Fermat's little theorem. Note that this only
    // works when n_ and Mod are relatively prime. The theorem says that
    // n_^(Mod-1) = 1 (mod Mod). So we can compute n_^(Mod-2).
    return Pow(Mod - 2);
  }
  long long value() const { return n_; }

  static ModInt Fact(int n) {
    for (int i = fact_.size(); i <= n; ++i) {
      fact_.push_back(i == 0 ? 1 : fact_.back() * i);
    }
    return fact_[n];
  }
  static ModInt Comb(int n, int k) { return Perm(n, k) / Fact(k); }
  static ModInt CombSlow(int n, int k) { return PermSlow(n, k) / Fact(k); }
  static ModInt Perm(int n, int k) {
#if DEBUG
    assert(n <= 1000000 &&
           "n is too large. If k is small, consider using PermSlow.");
#endif
    return Fact(n) / Fact(n - k);
  }
  static ModInt PermSlow(int n, int k) {
    ModInt p = 1;
    for (int i = 0; i < k; ++i) {
      p *= (n - i);
    }
    return p;
  }

 private:
  long long n_;
  inline static std::vector<ModInt> fact_;
};

#define DEFINE(op)                                            \
  template <int Mod, typename T>                              \
  ModInt<Mod> operator op(const T& t, const ModInt<Mod>& m) { \
    return ModInt<Mod>(t) op m;                               \
  }
BIN_OPS(DEFINE)
CMP_OPS(DEFINE)
#undef DEFINE

template <int Mod>
std::ostream& operator<<(std::ostream& out, const ModInt<Mod>& m) {
  out << m.value();
  return out;
}

namespace pclib {
namespace internal {

template <typename T, typename U>
class DP {
  using Edge = typename BidirectedGraph<U>::Edge;
  struct Weight {
    Edge* edge;
    T result;
  };
  using MetaEdge = typename BidirectedGraph<Weight>::Edge;

 public:
  DP(const BidirectedGraph<U>& graph, std::function<T(T, T)> op2,
     std::function<T(const Edge&, T)> op1, T identity = T())
      : graph_(graph.NumVertices()), op2_(op2), op1_(op1), identity_(identity) {
    for (int i = 0; i < graph.NumVertices(); ++i) {
      for (const auto& e : graph.Edges(i)) {
        if (e->from > e->to) continue;
        auto [f, b] = graph_.AddEdge(e->from, e->to);
        f.weight.edge = e.get();
        b.weight.edge = e->back;
      }
    }
  }

  void Dfs(int root) {
    // Use a stack to avoid potential stack overflows.
    std::stack<std::tuple<MetaEdge*, bool>> s;
    s.emplace(nullptr, true);

    while (!s.empty()) {
      auto [in_edge, enter] = s.top();
      s.pop();

      int node = in_edge ? in_edge->to : root;
      if (enter) {
        s.emplace(in_edge, false);
        for (const auto& e : graph_.Edges(node)) {
          if (e->back != in_edge) {
            s.emplace(e.get(), true);
          }
        }
      } else {
        T t = identity_;
        for (const auto& e : graph_.Edges(node)) {
          if (e->back != in_edge) {
            t = op2_(t, e->weight.result);
          }
        }
        if (in_edge) {
          in_edge->weight.result = op1_(*in_edge->weight.edge, t);
        }
      }
    }
  }

  std::vector<T> Rerooting(int root) {
    std::vector<T> result(graph_.NumVertices());

    std::stack<std::tuple<const MetaEdge*, T>> s;
    s.emplace(nullptr, identity_);

    while (!s.empty()) {
      auto [in_edge, in_result] = s.top();
      s.pop();

      if (in_edge) {
        in_edge->back->weight.result = in_result;
      }

      int node = in_edge ? in_edge->to : root;
      const auto& edges = graph_.Edges(node);

      // lower[i] = op2_(dp[i - 1], op2_(dp[i - 2], ...))
      std::vector<T> lower(edges.size() + 1);
      lower[0] = identity_;
      for (std::size_t i = 0; i < edges.size(); ++i) {
        lower[i + 1] = op2_(lower[i], edges[i]->weight.result);
      }

      // higher[i] = op2_(dp[i], op2_(dp[i + 1], ...))
      std::vector<T> higher(edges.size() + 1);
      higher[edges.size()] = identity_;
      for (std::size_t i = edges.size() - 1; i < edges.size(); --i) {
        higher[i] = op2_(higher[i + 1], edges[i]->weight.result);
      }

      result[node] = higher[0];

      for (std::size_t i = 0; i < edges.size(); ++i) {
        if (const auto& e = edges[i]; e->back != in_edge) {
          s.emplace(e.get(),
                    op1_(*e->back->weight.edge, op2_(lower[i], higher[i + 1])));
        }
      }
    }
    return result;
  }

  BidirectedGraph<Weight> graph_;

  const std::function<T(T, T)> op2_;
  const std::function<T(const Edge&, T)> op1_;
  const T identity_;
};

}  // namespace internal
}  // namespace pclib

template <typename T, typename U>
std::vector<T> Rerooting(
    const BidirectedGraph<U>& graph, std::function<T(T, T)> op2,
    std::function<T(const typename BidirectedGraph<U>::Edge&, T)> op1,
    T identity = T()) {
  pclib::internal::DP dp(graph, op2, op1, identity);
  dp.Dfs(0);
  return dp.Rerooting(0);
}

using mint = ModInt<>;

struct DP {
  mint sqsum;
  mint sum;
  mint cnt;
};

void Main() {
  ints(n);
  BidirectedGraph<int> g(n);
  rep(n - 1) {
    ints(a, b);
    g.AddEdge(a - 1, b - 1);
  }
  auto f = [](DP x) -> DP {
    // 1 -> 2 -> 3
    //
    // S3 = {1}
    // S2-3 = {0, 1}
    // S2 = {1, 2}
    // S1-2 = {0, 0, 1, 2}
    // S1 = {1, 1, 2, 3}
    //
    // S2-3 = {0, 1} = {0} + {1}
    // S2 = {0, 1}
    // S1-2 = {0, 0, 1, 2}  = {0, 0} + {1, 2}
    //
    // 1 -> 2
    //   -> 3
    //
    // S2 = {1}
    // S3 = {1}
    // S1-2 = {0, 1}
    // S1-3 = {0, 1}
    // S1 = {1, 2, 2, 3}
    //
    // S1-2 = {0, 1}
    // S1-3 = {0, 1}
    // S1 = {0, 1, 1, 2}
    // {a, b} {x, y}
    // {a+b
    mint cnt = x.cnt * 2;
    mint sum = x.sum + x.cnt;
    mint sqsum = x.sqsum + 2 * x.sum + x.cnt;
    return {sqsum, sum, cnt};
  };
  V<DP> res = Rerooting<DP, int>(
      g,
      [](DP a, DP b) -> DP {
        if (a.sum == 0) return b;
        if (b.sum == 0) return a;
        return {a.sqsum * b.cnt + 2 * a.sum * b.sum + b.sqsum * a.cnt,
                a.sum * b.cnt + b.sum * a.cnt, a.cnt * b.cnt};
      },
      [&](const auto&, DP x) -> DP { return f(x); }, {0, 0, 1});
  mint ans = 0;
  each(r, res) {
    ans += f(r).sqsum;
    dbg(r.sqsum, r.sum, r.cnt, f(r).sqsum);
    // 3 2 1 1 = 7
    // 9 4 1 1 = 15
    // 3 2 2 1
    // 9 4 4 1 = 18
  }
  wt(ans);
}
0