Problem:
C: Fractal Tree
問題
AORイカちゃんは、フラクタルな(自己相似的な)構造を持つ根付き木が好きである。
$N$ 頂点から成る重み付き根付き木 $T$ を用いて、以下のようなフラクタル構造を持つ根付き木 $T'$ を表現することを考える。
$T'$ は、$T$ の各頂点 $x$ に対して、$x$ を根として $T$ と同様の木構造 (コストも同じ) を持つ木を付け加えたものである。
$T'$の根は $T$ のものと同じものである。
こうして表現される木は例えば下図のようになる。
AOR イカちゃんは、$T'$ に対して深さ優先探索をしようとしているが、全ての頂点を辿ると時間がとてもかかることに気づいた。
そこで、深さ優先探索時の遷移の際に確率 $p$ で遷移し、確率 $1-p$ で遷移しない方針で深さ優先探索を行い、いくつかのノード訪問をサボることにした。
$T$ と確率 $p$ が与えられるので、$T’$ に対して深さ優先探索を行う際に辿る全ての辺のコストの和の期待値を求めよ。
$T$ の情報は頂点数 $N$ と $N-1$ 本の辺の情報で与えられ、頂点 $1$ が根である。
各頂点は $1,2,\dots,N$ とラベリングされており、 $i \ (1 \le i \le N-1)$ 番目の辺は頂点 $x_i$ と $y_i$ をコスト $c_i$ で結んでいる。
今回の問題で扱う、確率 $p$ で子に遷移する深さ優先探索の非決定的アルゴリズムは以下のように表現される。
出力される $\mathrm{answer}$ が辿る辺のコストの総和である。
空のスタック $S$ を用意する。
$\mathrm{answer}=0$ とする
$S$ に $T'$ の根頂点をプッシュする。
$S$ の先頭の要素を取り出し、これを $x$ とする。
$x$ の各子 $c$ に対し、それぞれ確率 $p$ で次の操作を行い、確率 $1-p$ で何もしない。
$S$ に頂点 $c$ を追加する。そして $\mathrm{answer}$ に $x$ から $c$ に繋がっている辺の重みを加える。
Sが空でなければ、3. に遷移する。
$\mathrm{answer}$ を出力する。
制約
$2 \le N \le 10^5$
$0 \le p \le 1.0$ (小数点第 2 位まで与えられる。)
$1 \le x_i,y_i \le N$
$1 \le c_i \le 1000$
$c_i$ は整数である
与えられるグラフは $N$ 頂点の根付き木である。すなわち、頂点 $N$、辺数 $N-1$、連結という性質を持つグラフであり、頂点 $1$ が根である。
入力形式
入力は以下の形式で与えられる。
$p$
$N$
$x_1 \ y_1 \ c_1$
$\vdots$
$x_{N-1} \ y_{N-1} \ c_{N-1}$
出力
答えを 1 行で出力せよ。相対誤差または絶対誤差が $10^{-6}$ 以下なら AC となる。また、末尾に改行も出力せよ。
サンプル
サンプル入力1
0.75
4
1 2 1
2 3 3
3 4 10
サンプル出力1
24.8569335938
サンプル入力2
0.75
4
1 2 1
1 3 3
3 4 10
サンプル出力2
35.0390625
問題文の図の木を与える例である。

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
#include <vector>
using namespace std;
int inf=100000000;
using ll=long long;
using pint=pair<int,int>;
using pll=pair<ll,ll>;
using pque_int=priority_queue<int>;
#define rep(i,n) for (int i=0; i < (int) n; i++)
#define _GLIBCXX_DEBUG
template<typename T> inline bool chmax(T &a, T b) { return ((a < b) ? (a = b, true) : (false)); }
template<typename T> inline bool chmin(T &a, T b) { return ((a > b) ? (a = b, true) : (false)); }
int VecMax(vector<int> &v) {
    int output=-inf;
    rep(i,v.size()) chmax(output,v[i]);
    return output;
}
int VecMin(vector<ll> &v) {
    ll output=inf;
    rep(i,v.size()) chmin(output,v[i]);
    return output;
}
ll VecSum(vector<int> &v) {
    ll output=0;
    rep(i,v.size()) output+=v[i];
    return output;
}
ll pow(ll a,ll n) {
    ll output=1;
    while (n>0) output*=a;
    return output;
}
int dir(char c) {
    if (c=='L') return 3;
    else if (c=='R') return 1;
    else if (c=='U') return 2;
    else return 0;
}

int main() {
    double p;
    int N;
    cin >> p >> N;
    vector<int> x(N-1),y(N-1);
    map<pint,int> c;
    rep(i,N-1) {
        cin >> x[i] >> y[i];
        x[i]--; y[i]--;
        int in;
        cin >> in;
        c[make_pair(x[i],y[i])]=in;
        c[make_pair(y[i],x[i])]=in;
    }
    vector<double> power_p(N+1);
    double s=1;
    rep(i,N) {
        power_p[i]=s;
        s*=p;
    }
    power_p[N]=s;


    vector<vector<int>> graph(N);
    rep(i,N) {
        graph[x[i]].push_back(y[i]);
        graph[y[i]].push_back(x[i]);
    }
    deque<int> todo;
    todo.push_back(0);
    vector<int> seen(N,-1);
    vector<double> score(N,-1.0);
    seen[0]=0;
    score[0]=0.0;
    vector<int> end;
    while(!todo.empty()) {
        int x=todo.back();
        todo.pop_back();
        bool flag=true;
        for (auto nx:graph[x]) {
            if (seen[nx]<0) {
                seen[nx]=seen[x]+1;
                score[nx]= c[make_pair(x,nx)]*power_p[seen[nx]];
                todo.push_back(nx);
                flag=false;
            } 
        }
        if (flag) {
            end.push_back(x);
        }
    }
    double endscore=0;
    rep(i,N) {
        endscore+=score[i];
    }

    double ans=0;
    rep(i,N) {
        ans+=power_p[seen[i]]*endscore+score[i];
    }
    cout << std::fixed << std::setprecision(9);
    cout << ans << endl;
}
accuracy: 1
time_ms: 130
memory_kb: 24316
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;

typedef long long ll;

#define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++)
#define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--)

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

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

template <typename T> T max(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmax(ret, a[i]);
	return ret;
}

template <typename T> T min(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmin(ret, a[i]);
	return ret;
}

template <typename T> T sum(vector<T> &a){
	T ret = 0;
	for (int i=0; i<(int)a.size(); i++) ret += a[i];
	return ret;
}

int main(){
	long double p; cin >> p;
	int n; cin >> n;

	vector ikeru(n, vector<pair<int,double>>(0));
	rep(i,0,n-1){
		int a, b; cin >> a >> b;
		a--; b--;
		long double c; cin >> c;
		ikeru[a].push_back(pair(b, c));
		ikeru[b].push_back(pair(a, c));


	}

	vector<long double> dp1(n), dp2(n);
	auto dfs = [&](auto self, int i, int x, vector<long double> &dp, long double geta) -> void {
		dp[i] += geta;
		for (auto [j, c]: ikeru[i]){
			if (j == x) continue;
			self(self, j, i, dp, geta);
			dp[i] += p * c;
			dp[i] += p * dp[j];
		}
	};

	

	dfs(dfs,0,-1,dp1,0);
	dfs(dfs,0,-1,dp2,dp1[0]);

	cout << fixed << setprecision(15);
	cout << dp2[0] << '\n';
}
accuracy: 1
time_ms: 60
memory_kb: 27340
final_rank: 12

code_snippet: #line 2 "/Users/noya2/Desktop/Noya2_library/template/template.hpp"
using namespace std;

#include<bits/stdc++.h>
#line 1 "/Users/noya2/Desktop/Noya2_library/template/inout_old.hpp"
namespace noya2 {

template <typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &p){
    os << p.first << " " << p.second;
    return os;
}
template <typename T, typename U>
istream &operator>>(istream &is, pair<T, U> &p){
    is >> p.first >> p.second;
    return is;
}

template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v){
    int s = (int)v.size();
    for (int i = 0; i < s; i++) os << (i ? " " : "") << v[i];
    return os;
}
template <typename T>
istream &operator>>(istream &is, vector<T> &v){
    for (auto &x : v) is >> x;
    return is;
}

void in() {}
template <typename T, class... U>
void in(T &t, U &...u){
    cin >> t;
    in(u...);
}

void out() { cout << "\n"; }
template <typename T, class... U, char sep = ' '>
void out(const T &t, const U &...u){
    cout << t;
    if (sizeof...(u)) cout << sep;
    out(u...);
}

template<typename T>
void out(const vector<vector<T>> &vv){
    int s = (int)vv.size();
    for (int i = 0; i < s; i++) out(vv[i]);
}

struct IoSetup {
    IoSetup(){
        cin.tie(nullptr);
        ios::sync_with_stdio(false);
        cout << fixed << setprecision(15);
        cerr << fixed << setprecision(7);
    }
} iosetup_noya2;

} // namespace noya2
#line 1 "/Users/noya2/Desktop/Noya2_library/template/const.hpp"
namespace noya2{

const int iinf = 1'000'000'007;
const long long linf = 2'000'000'000'000'000'000LL;
const long long mod998 =  998244353;
const long long mod107 = 1000000007;
const long double pi = 3.14159265358979323;
const vector<int> dx = {0,1,0,-1,1,1,-1,-1};
const vector<int> dy = {1,0,-1,0,1,-1,-1,1};
const string ALP = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string alp = "abcdefghijklmnopqrstuvwxyz";
const string NUM = "0123456789";

void yes(){ cout << "Yes\n"; }
void no(){ cout << "No\n"; }
void YES(){ cout << "YES\n"; }
void NO(){ cout << "NO\n"; }
void yn(bool t){ t ? yes() : no(); }
void YN(bool t){ t ? YES() : NO(); }

} // namespace noya2
#line 1 "/Users/noya2/Desktop/Noya2_library/template/utils.hpp"
namespace noya2{

unsigned long long inner_binary_gcd(unsigned long long a, unsigned long long b){
    if (a == 0 || b == 0) return a + b;
    int n = __builtin_ctzll(a); a >>= n;
    int m = __builtin_ctzll(b); b >>= m;
    while (a != b) {
        int mm = __builtin_ctzll(a - b);
        bool f = a > b;
        unsigned long long c = f ? a : b;
        b = f ? b : a;
        a = (c - b) >> mm;
    }
    return a << min(n, m);
}

template<typename T> T gcd_fast(T a, T b){ return static_cast<T>(inner_binary_gcd(abs(a),abs(b))); }

long long sqrt_fast(long long n) {
    if (n <= 0) return 0;
    long long x = sqrt(n);
    while ((x + 1) * (x + 1) <= n) x++;
    while (x * x > n) x--;
    return x;
}

template<typename T> T floor_div(const T n, const T d) {
    assert(d != 0);
    return n / d - static_cast<T>((n ^ d) < 0 && n % d != 0);
}

template<typename T> T ceil_div(const T n, const T d) {
    assert(d != 0);
    return n / d + static_cast<T>((n ^ d) >= 0 && n % d != 0);
}

template<typename T> void uniq(vector<T> &v){
    sort(v.begin(),v.end());
    v.erase(unique(v.begin(),v.end()),v.end());
}

template <typename T, typename U> inline bool chmin(T &x, U y) { return (y < x) ? (x = y, true) : false; }

template <typename T, typename U> inline bool chmax(T &x, U y) { return (x < y) ? (x = y, true) : false; }

template<typename T> inline bool range(T l, T x, T r){ return l <= x && x < r; }

} // namespace noya2
#line 8 "/Users/noya2/Desktop/Noya2_library/template/template.hpp"

#define rep(i,n) for (int i = 0; i < (int)(n); i++)
#define repp(i,m,n) for (int i = (m); i < (int)(n); i++)
#define reb(i,n) for (int i = (int)(n-1); i >= 0; i--)
#define all(v) (v).begin(),(v).end()

using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using pil = pair<int,ll>;
using pli = pair<ll,int>;

namespace noya2{

/*　~ (. _________ . /)　*/

}

using namespace noya2;


#line 2 "c.cpp"


void solve(){
    ld p; in(p);
    int n; in(n);
    using pid = pair<int,ld>;
    vector<vector<pid>> g(n);
    rep(i,n-1){
        int u, v; in(u,v); u--, v--;
        ld c; in(c);
        g[u].emplace_back(v,c);
        g[v].emplace_back(u,c);
    }
    ld sum = 0;
    auto dfs = [&](auto sfs, int v, int f, ld pp) -> void {
        for (auto [u, c] : g[v]){
            if (u == f) continue;
            sum += pp*p * c;
            sfs(sfs,u,v,pp*p);
        }
    };
    dfs(dfs,0,-1,1);
    ld ans = sum;
    auto efs = [&](auto sfs, int v, int f, ld pp) -> void {
        ans += pp * sum;
        for (auto [u, c] : g[v]){
            if (u == f) continue;
            sfs(sfs,u,v,pp*p);
        }
    };
    efs(efs,0,-1,1);
    out(ans);
}

int main(){
    int t = 1; //in(t);
    while (t--) { solve(); }
}
accuracy: 1
time_ms: 40
memory_kb: 22676
final_rank: 8

code_snippet: #pragma region //comavius::competitive library

#pragma region //inclusion and optimization
#include <bits/stdc++.h>
#ifdef IS_TEST
static const bool IS_TEST_ENVIROMENT = true;
#else
static const bool IS_TEST_ENVIROMENT = false;
#endif
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma endregion //inclusion and optimization

namespace comavius::competitive { //typedefs

    #pragma region //long long
        typedef long long ll;
        typedef std::vector<ll> vll;
        typedef std::vector<vll> vvll;
        typedef std::vector<vvll> vvvll;
        typedef std::map<ll, ll> mll;
        typedef std::map<ll, mll> mmll;
        typedef std::pair<ll, ll> pll;
        typedef std::vector<pll> vpll;
    #pragma endregion //long long

    #pragma region //long double
        typedef long double ld;
        typedef std::vector<ld> vld;
        typedef std::vector<vld> vvld;
        typedef std::vector<vvld> vvvld;
    #pragma endregion //long double

    #pragma region //std::string
    typedef std::string str;
    typedef std::vector<str> vstr;
    typedef std::vector<vstr> vvstr;
    typedef std::vector<vvstr> vvvstr;
    #pragma endregion //std::string

    #pragma region //bool
        typedef std::vector<bool> vb;
        typedef std::vector<vb> vvb;
        typedef std::vector<vvb> vvvb;
    #pragma endregion //bool

    #pragma region //char
        typedef std::vector<char> vc;
        typedef std::vector<vc> vvc;
        typedef std::vector<vvc> vvvc;
    #pragma endregion //char

    #pragma region //container of std
        #pragma region //std::vector
            template <typename T>
            using vec = std::vector<T>;
            template <typename T>
            using vec2 = std::vector<std::vector<T>>;
            template <typename T>
            using vec3 = std::vector<std::vector<std::vector<T>>>;
            template <typename T>
            using vec4 = std::vector<std::vector<std::vector<std::vector<T>>>>;
            template <typename T>
            using vec5 = std::vector<std::vector<std::vector<std::vector<std::vector<T>>>>>;
            template <typename T>
            using vec6 = std::vector<std::vector<std::vector<std::vector<std::vector<std::vector<T>>>>>>;
            template <typename T>
            using vec7 = std::vector<std::vector<std::vector<std::vector<std::vector<std::vector<std::vector<T>>>>>>>;
        #pragma endregion //std::vector
    #pragma endregion //container of std

} // namespace comavius::competitive typedefs


#pragma region //Read macro
    #define GET_1_ARG(TYPE, ARG); TYPE ARG; std::cin >> ARG;
    #define GET_2_ARG(TYPE, ARG, ...) GET_1_ARG(TYPE, ARG) GET_1_ARG(TYPE, __VA_ARGS__)
    #define GET_3_ARG(TYPE, ARG, ...) GET_1_ARG(TYPE, ARG) GET_2_ARG(TYPE, __VA_ARGS__)
    #define GET_4_ARG(TYPE, ARG, ...) GET_1_ARG(TYPE, ARG) GET_3_ARG(TYPE, __VA_ARGS__)
    #define GET_5_ARG(TYPE, ARG, ...) GET_1_ARG(TYPE, ARG) GET_4_ARG(TYPE, __VA_ARGS__)
    #define GET_6_ARG(TYPE, ARG, ...) GET_1_ARG(TYPE, ARG) GET_5_ARG(TYPE, __VA_ARGS__)
    #define GET_7_ARG(TYPE, ARG, ...) GET_1_ARG(TYPE, ARG) GET_6_ARG(TYPE, __VA_ARGS__)
    #define GET_8_ARG(TYPE, ARG, ...) GET_1_ARG(TYPE, ARG) GET_7_ARG(TYPE, __VA_ARGS__)
    #define GET_9_ARG(TYPE, ARG, ...) GET_1_ARG(TYPE, ARG) GET_8_ARG(TYPE, __VA_ARGS__)
    #define GET_10_ARG(TYPE, ARG, ...) GET_1_ARG(TYPE, ARG) GET_9_ARG(TYPE, __VA_ARGS__)

    #define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,NAME,...) NAME
    #define read(TYPE, ...) GET_MACRO(__VA_ARGS__, GET_10_ARG, GET_9_ARG, GET_8_ARG, GET_7_ARG, GET_6_ARG, GET_5_ARG, GET_4_ARG, GET_3_ARG, GET_2_ARG, GET_1_ARG)(TYPE, __VA_ARGS__)

    #define readv(TYPE, NAME, SIZE) std::vector<TYPE> NAME(SIZE); for (long long i = 0; i < SIZE; i++) std::cin >> NAME[i];
    #define readvv(TYPE, NAME, H, W) std::vector<std::vector<TYPE>> NAME(H, std::vector<TYPE>(W)); for (long long i = 0; i < H; i++) for (long long j = 0; j < W; j++) std::cin >> NAME[i][j];
#pragma endregion //Read macro

#pragma region //Other macro
    #define rep(i, n) for (ll i = 0; i < n; i++)
    #define reps(i, start, goal, diff) for (ll i = start; i != goal; i += diff)
    #define all(a) a.begin(), a.end()
//    #define chmax(a, b) a = std::max(a, b)
//    #define chmin(a, b) a = std::min(a, b)
#pragma endregion //Other macro

#pragma region //namespace expansion
    using namespace std;
    using namespace comavius::competitive;
#pragma endregion //namespace expansion

#pragma endregion //comavius::competitive library



#pragma region // fundamental structures

using vvpll = vector<vpll>;

int main() {
    read(ld, p);
    read(ll, n);
    vvpll adj(n);
    rep(i, n-1) {
        read(ll,x,y,c);
        x--;y--;
        adj[x].push_back({y, c});
        adj[y].push_back({x, c});
    }
    vld reach_prob(n, 0);
    reach_prob[0] = 1;
    ld cost_sum = 0;
    queue<ll> q;
    q.push(0);
    vb visited(n, false);
    visited[0] = true;
    while(q.size()) {
        ll cur = q.front();
        q.pop();
        for (auto [next, cost] : adj[cur]) {
            if (visited[next]) continue;
            reach_prob[next] = reach_prob[cur] * p;
            cost_sum += ll(cost) * reach_prob[next];
            q.push(next);
            visited[next] = true;
        }
    }
    ld cost_fr = cost_sum;
    rep(i, n) {
        cost_fr += cost_sum * reach_prob[i];
    }
    cout << setprecision(15) << cost_fr << endl;
}
accuracy: 1
time_ms: 50
memory_kb: 12144
final_rank: 4

code_snippet: //#include<atcoder/all>
//using namespace atcoder;

#include <bits/stdc++.h>
template<class T> inline bool chmin(T&a, T b){if(a > b){a = b; return true;}else{return false;}}
template<class T> inline bool chmax(T&a, T b){if(a < b){a = b; return true;}else{return false;}}
#define ll long long
#define double long double
#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=1;i<=(n);i++)
#define mod (ll)(1e9+7)
#define inf (ll)(3e18+7)
#define eps (double)(1e-9)
#define pi (double) acos(-1)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
using namespace std;

struct edge{
    int to, cost;
};

using Graph = vector<vector<edge>>;

double P;
vector<double> dp1(100010, -1);
vector<double> dp2(100010, -1);

double dfs1(const Graph &G, int v, int p){
    if(dp1[v] != -1)return dp1[v];

    double now = 0;
    for(auto nv : G[v]){
        if(nv.to == p)continue;
        now += P * (dfs1(G, nv.to, v) + nv.cost);
    }

    return dp1[v] = now;
}

double dfs2(const Graph &G, int v, int p){
    if(dp2[v] != -1)return dp2[v];
    
    double now = 0;
    for(auto nv : G[v]){
        if(nv.to == p)continue;
        now += P * (dfs2(G, nv.to, v) + nv.cost);
    }
    now += dp1[0];

    return dp2[v] = now;
}

int main(){
    int n;
    cin >> P >> n;
    Graph G(n);
    rep(i, n-1){
        int x, y, z;
        cin >> x >> y >> z;
        x--; y--;
        G[x].push_back({y, z});
        G[y].push_back({x, z});
    }

    dfs1(G, 0, -1);
    dfs2(G, 0, -1);

    cout << fixed << setprecision(15) << dp2[0] << endl;
}
accuracy: 1
time_ms: 60
memory_kb: 21084
final_rank: 9

code_snippet: // #ifndef ONLINE_JUDGE
#if __has_include("all.h")

#include "all.h"

#else

#include <bits/extc++.h>

// #include <atcoder/all>

#endif

using ll = long long int;

template <class T>
bool chmin(T &x, const T val) {
  if (x > val) {
    x = val;
    return true;
  } else {
    return false;
  }
}

template <class T>
bool chmax(T &x, const T val) {
  if (x < val) {
    x = val;
    return true;
  } else {
    return false;
  }
}

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

template <class... T>
std::istream &operator>>(std::istream &is, std::tuple<T...> &tpl) {
  std::apply([&](auto &&...args) { (is >> ... >> args); }, tpl);
  return is;
}

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

// template <class mint, atcoder::internal::is_static_modint_t<mint> * =
// nullptr> std::ostream &operator<<(std::ostream &os, const mint &v) {
//   return os << v.val();
// }

template <class T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
  for (int i = 0; i < v.size(); i++)
    os << v[i] << (i == v.size() - 1 ? "" : " ");
  return os;
}

struct Initialization {
  Initialization() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
  }
} initialization;

constexpr std::pair<int, int> dir[] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

template <typename T>
using infs = std::numeric_limits<T>;

template <typename T>
class factorials {
 public:
  static size_t n;
  static std::vector<T> fact, inv_fact;

  static void extend(size_t m) {
    if (m <= n) return;
    fact.resize(m + 1);
    inv_fact.resize(m + 1);
    for (size_t i = n + 1; i <= m; i++) fact[i] = fact[i - 1] * i;
    inv_fact[m] = fact[m].inv();
    for (size_t i = m; i > n + 1; i--) inv_fact[i - 1] = inv_fact[i] * i;
    n = m;
  }

  static T inv(int k) {
    extend(k);
    return inv_fact[k];
  }

  static T get(int k) {
    extend(k);
    return fact[k];
  }

  static T perm(int n, int k) {
    if (n < k) return 0;
    if (k < 0) return 0;
    extend(n);
    return fact[n] * inv_fact[n - k];
  }

  static T choose(int n, int k) {
    if (n < k) return 0;
    if (k < 0) return 0;
    extend(n);
    return fact[n] * inv_fact[n - k] * inv_fact[k];
  }
};

template <typename T>
size_t factorials<T>::n = 0;

template <typename T>
std::vector<T> factorials<T>::fact = {1};

template <typename T>
std::vector<T> factorials<T>::inv_fact = {1};

// template <typename T>
// class fps {
//   std::vector<T> v;
//
//  public:
//   using value_type = T;
//   using reference = T &;
//   using const_reference = const T &;
//   using iterator = typename std::vector<T>::iterator;
//   using const_iterator = typename std::vector<T>::const_iterator;
//
//   size_t size() const { return v.size(); }
//
//   const std::vector<T> &data() const { return v; }
//
//   explicit fps(int n) : v(n) {}
//
//   fps(const std::vector<T> &v) : v(v) {}
//   fps(std::vector<T> &&v) : v(v) {}
//
//   template <class InputIterator>
//   fps(InputIterator first, InputIterator last) : v(first, last) {}
//
//   void resize(int n) { v.resize(n); }
//
//   T &operator[](int i) { return v[i]; }
//
//   iterator begin() { return v.begin(); }
//
//   iterator end() { return v.end(); }
//
//   fps diff() {
//     std::vector<T> res(v.size() - 1);
//     for (int i = 0; i < res.size(); i++) res[i] = v[i + 1] * (i + 1);
//     return fps(res);
//   }
//
//   fps integral() {
//     std::vector<T> res(v.size() + 1);
//     for (int i = 0; i < v.size(); i++) res[i + 1] = v[i] / (i + 1);
//     return fps(res);
//   }
//
//   fps inv(int deg = -1) {
//     assert(v[0] != 0);
//
//     if (deg == -1) deg = size();
//     std::vector<T> res(deg);
//
//     res[0] = v[0].inv();
//
//     for (int d = 1; d < deg; d <<= 1) {
//       std::vector<T> f(2 * d), g(2 * d);
//
//       std::copy(v.begin(), v.begin() + std::min(2 * d, (int)v.size()),
//                 std::back_inserter(f));
//       std::copy(res.begin(), res.begin() + d, std::back_inserter(g));
//
//       atcoder::internal::butterfly(f);
//       atcoder::internal::butterfly(g);
//
//       for (int i = 0; i < 2 * d; i++) f[i] *= g[i];
//
//       atcoder::internal::butterfly_inv(f);
//
//       for (int i = 0; i < d; i++) f[i] = 0;
//
//       atcoder::internal::butterfly(f);
//
//       for (int i = 0; i < 2 * d; i++) f[i] *= g[i];
//
//       atcoder::internal::butterfly_inv(f);
//
//       for (int i = d; i < std::min(2 * d, deg); i++) res[i] = -f[i];
//     }
//
//     res.resize(deg);
//
//     return res;
//   }
//
//   fps shift(T c) {
//     std::vector<T> res(size()), ifacts(size());
//
//     T x = 1;
//
//     for (int i = 0; i < size(); i++) {
//       ifacts[i] = x * factorials<T>::inv(i);
//       x *= c;
//     }
//
//     for (int i = 0; i < size(); i++) {
//       res[size() - 1 - i] = v[i] * factorials<T>::get(i);
//     }
//
//     res = atcoder::convolution(res, ifacts);
//
//     res.resize(size());
//
//     std::ranges::reverse(res);
//
//     for (int i = 0; i < size(); i++) {
//       res[i] *= factorials<T>::inv(i);
//     }
//
//     return res;
//   }
//
//   fps operator-() {
//     fps res(v.size());
//     for (int i = 0; i < v.size(); i++) res[i] = -v[i];
//     return res;
//   }
//
//   fps &operator+=(const fps &rhs) {
//     if (v.size() < rhs.v.size()) v.resize(rhs.v.size());
//     for (int i = 0; i < rhs.v.size(); i++) v[i] += rhs.v[i];
//     return *this;
//   }
//
//   fps &operator-=(const fps &rhs) {
//     if (v.size() < rhs.v.size()) v.resize(rhs.v.size());
//     for (int i = 0; i < rhs.v.size(); i++) v[i] -= rhs.v[i];
//     return *this;
//   }
//
//   fps &operator*=(const fps &rhs) {
//     return *this = atcoder::convolution(v, rhs.v);
//   }
//
//   fps &operator+=(const T &rhs) {
//     if (v.size() == 0) v.resize(1);
//     v[0] += rhs;
//     return *this;
//   }
//
//   fps &operator-=(const T &rhs) {
//     if (v.size() == 0) v.resize(1);
//     v[0] -= rhs;
//     return *this;
//   }
//
//   fps &operator*=(const T &rhs) {
//     for (int i = 0; i < v.size(); i++) v[i] *= rhs;
//     return *this;
//   }
//
//   fps &operator/=(const T &rhs) {
//     T rhs_inv = rhs.inv();
//     for (int i = 0; i < v.size(); i++) v[i] *= rhs_inv;
//     return *this;
//   }
//
//   friend fps operator+(const fps &lhs, const fps &rhs) {
//     return fps(lhs) += rhs;
//   }
//
//   friend fps operator-(const fps &lhs, const fps &rhs) {
//     return fps(lhs) -= rhs;
//   }
//
//   friend fps operator*(const fps &lhs, const fps &rhs) {
//     return fps(lhs) *= rhs;
//   }
//
//   friend fps operator+(const fps &lhs, const T &rhs) { return fps(lhs) +=
//   rhs; }
//
//   friend fps operator-(const fps &lhs, const T &rhs) { return fps(lhs) -=
//   rhs; }
//
//   friend fps operator*(const fps &lhs, const T &rhs) { return fps(lhs) *=
//   rhs; }
//
//   friend fps operator/(const fps &lhs, const T &rhs) { return fps(lhs) /=
//   rhs; }
//
//   friend fps operator+(const T &lhs, const fps &rhs) { return fps(rhs) +=
//   lhs; }
//
//   friend fps operator-(const T &lhs, const fps &rhs) {
//     return -(fps(rhs) -= lhs);
//   }
//
//   friend fps operator*(const T &lhs, const fps &rhs) { return fps(rhs) *=
//   lhs; }
// };

// using mint = atcoder::modint998244353;
// using mint = atcoder::modint1000000007;

// using fs = factorials<mint>;

int main() {
  double p;
  ll N;
  std::cin >> p >> N;

  std::vector graph(N, std::vector<std::pair<int, int>>());

  for (int i = 0; i < N - 1; i++) {
    int x, y, c;
    std::cin >> x >> y >> c;
    x--;
    y--;
    graph[x].emplace_back(y, c);
    graph[y].emplace_back(x, c);
  }

  auto rec1 = [&](auto self, int v, int par = -1) -> double {
    double result = 0;

    for (auto [w, c] : graph[v]) {
      if (par == w) continue;
      result += p * (c + self(self, w, v));
    }

    return result;
  };

  double orig = rec1(rec1, 0);

  auto rec2 = [&](auto self, int v, int par = -1) -> double {
    double result = orig;

    for (auto [w, c] : graph[v]) {
      if (par == w) continue;
      result += p * (c + self(self, w, v));
    }

    return result;
  };

  std::cout << std::fixed << std::setprecision(15) << rec2(rec2, 0)
            << std::endl;
}
accuracy: 1
time_ms: 20
memory_kb: 18012
final_rank: 3

code_snippet: #include <bits/stdc++.h>
//#include <atcoder/all>
//using namespace atcoder;
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
using namespace std;
 
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<int, int> pii;
typedef pair<long long, long long> PLL;
typedef pair<int, PII> TIII;
 
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
 
 
#define FOR(i, s, n) for (int i = s; i < (int)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define trav(a, x) for (auto &a : x)
#define all(x) x.begin(), x.end()
 
#define MOD 1000000007
 
template<class T1, class T2> inline bool chmax(T1 &a, T2 b) {if (a < b) {a = b; return true;} return false;}
template<class T1, class T2> inline bool chmin(T1 &a, T2 b) {if (a > b) {a = b; return true;} return false;}
const double EPS = 1e-8, PI = acos(-1);
const double pi = 3.141592653589793238462643383279;
//ここから編集    
typedef string::const_iterator State;
ll GCD(ll a, ll b){
  return (b==0)?a:GCD(b, a%b);
}
ll LCM(ll a, ll b){
  return a/GCD(a, b) * b;
}
template< int mod >
struct ModInt {
  int x;
 
  ModInt() : x(0) {}
 
  ModInt(int64_t y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}
 
  ModInt &operator+=(const ModInt &p) {
    if((x += p.x) >= mod) x -= mod;
    return *this;
  }
 
  ModInt &operator-=(const ModInt &p) {
    if((x += mod - p.x) >= mod) x -= mod;
    return *this;
  }
 
  ModInt &operator*=(const ModInt &p) {
    x = (int) (1LL * x * p.x % mod);
    return *this;
  }
 
  ModInt &operator/=(const ModInt &p) {
    *this *= p.inverse();
    return *this;
  }
 
  ModInt operator-() const { return ModInt(-x); }
 
  ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }
 
  ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }
 
  ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }
 
  ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }
 
  bool operator==(const ModInt &p) const { return x == p.x; }
 
  bool operator!=(const ModInt &p) const { return x != p.x; }
 
  ModInt inverse() const {
    int a = x, b = mod, u = 1, v = 0, t;
    while(b > 0) {
      t = a / b;
      swap(a -= t * b, b);
      swap(u -= t * v, v);
    }
    return ModInt(u);
  }
 
  ModInt pow(int64_t n) const {
    ModInt ret(1), mul(x);
    while(n > 0) {
      if(n & 1) ret *= mul;
      mul *= mul;
      n >>= 1;
    }
    return ret;
  }
 
  friend ostream &operator<<(ostream &os, const ModInt &p) {
    return os << p.x;
  }
 
  friend istream &operator>>(istream &is, ModInt &a) {
    int64_t t;
    is >> t;
    a = ModInt< mod >(t);
    return (is);
  }
 
  static int get_mod() { return mod; }
};
 
using modint = ModInt< 998244353 >;
template< typename T >
struct Combination {
  vector< T > _fact, _rfact, _inv;
 
  Combination(int sz) : _fact(sz + 1), _rfact(sz + 1), _inv(sz + 1) {
    _fact[0] = _rfact[sz] = _inv[0] = 1;
    for(int i = 1; i <= sz; i++) _fact[i] = _fact[i - 1] * i;
    _rfact[sz] /= _fact[sz];
    for(int i = sz - 1; i >= 0; i--) _rfact[i] = _rfact[i + 1] * (i + 1);
    for(int i = 1; i <= sz; i++) _inv[i] = _rfact[i] * _fact[i - 1];
  }
 
  inline T fact(int k) const { return _fact[k]; }
 
  inline T rfact(int k) const { return _rfact[k]; }
 
  inline T inv(int k) const { return _inv[k]; }
 
  T P(int n, int r) const {
    if(r < 0 || n < r) return 0;
    return fact(n) * rfact(n - r);
  }
 
  T C(int p, int q) const {
    if(q < 0 || p < q) return 0;
    return fact(p) * rfact(q) * rfact(p - q);
  }
 
  T H(int n, int r) const {
    if(n < 0 || r < 0) return (0);
    return r == 0 ? 1 : C(n + r - 1, r);
  }
};
 
ll modpow(ll x, ll n, ll mod) {
  ll res = 1;
  x %= mod;
  if(x == 0) return 0;
  while(n) {
    if(n&1) res = (res * x) % mod;
    x = (x * x) % mod;
    n >>= 1;
  }
  return res;
} 
inline long long mod(long long a, long long m) {
    return (a % m + m) % m;
}
template<typename T> 
struct BIT{
  int N;
  std::vector<T> node;
  BIT(){}
  BIT(int n){
    N = n;
    node.resize(N+10);
  }
  void build(int n) {
    N = n;
    node.resize(N+10);
  }
  /* a: 1-indexed */
  void add(int a, T x){
    for(int i=a; i<(int)node.size(); i += i & -i) node[i] += x;
  }

  /* [1, a] */
  T sum(int a){
    T res = 0;
    for(int x=a; x>0; x -= x & -x) res += node[x];
    return res;
  }

  /* [l, r] */
  T rangesum(int l, int r){
    return sum(r) - sum(l-1);
  }

  /* 
    a1+a2+...+aw >= valとなるような最小のwを返す
    @verify https://codeforces.com/contest/992/problem/E
  */
  int lower_bound(T val) {
    if(val < 0) return 0;

    int res = 0;
    int n = 1; 
    while (n < N) n *= 2;

    T tv=0;
    for (int k = n; k > 0; k /= 2) {
      if(res + k < N && node[res + k] < val){
        val -= node[res+k];
        res += k;
      }
    }
    return res+1; 
  }
};
struct UnionFind{
  std::vector<int> par;
  std::vector<int> siz;

  UnionFind(int sz_): par(sz_), siz(sz_) {
    for(int i=0; i<sz_; ++i) par[i] = i, siz[i] = 1;
  }

  void init(int sz_){
    par.resize(sz_);
    siz.resize(sz_);
    for(int i=0; i<sz_; ++i) par[i] = i, siz[i] = 1;
  }

  int root(int x){
    if(x == par[x]) return x;
    return par[x] = root(par[x]);
  }

  bool merge(int x, int y){
    x = root(x), y = root(y);
    if(x == y) return false;
    if(siz[x] < siz[y]) std::swap(x, y);
    siz[x] += siz[y];
    par[y] = x;
    return true;
  }

  bool issame(int x, int y){
    return root(x) == root(y);
  }

  int size(int x){
    return siz[root(x)];
  }
};
struct RollingHash{

    using ull = unsigned long long;
    const ull mod = (1ULL << 61) - 1;
    const ull MASK30 = (1ULL << 30) - 1;
    const ull MASK31 = (1ULL << 31) - 1;

    const ull MASK61 = mod;

    ull base;
    int n;
    vector<ull> hash, pow;

    RollingHash(const string &s)
    {
        random_device rnd;
        mt19937_64 mt(rnd());
        base = 1001;
        
        n = (int)s.size();
        hash.assign(n+1, 0);
        pow.assign(n+1, 1);
        
        for(int i=0; i<n; i++){
            hash[i+1] = calc_mod(mul(hash[i], base) + s[i]);
            pow[i+1] = calc_mod(mul(pow[i], base));
        }
    }

    ull calc_mod(ull x){
        ull xu = x >> 61;
        ull xd = x & MASK61;
        ull res = xu + xd;
        if(res >= mod) res -= mod;
        return res;
    }

    ull mul(ull a, ull b){
        ull au = a >> 31;
        ull ad = a & MASK31;
        ull bu = b >> 31;
        ull bd = b & MASK31;
        ull mid = ad * bu + au * bd;
        ull midu = mid >> 30;
        ull midd = mid & MASK30;
        return calc_mod(au * bu * 2 + midu + (midd << 31) + ad * bd);
    }

    //[l,r)のハッシュ値
    inline ull get(int l, int r){
        ull res = calc_mod(hash[r] + mod*3-mul(hash[l], pow[r-l]));
        return res;
    }
    //string tのハッシュ値
    inline ull get(string t){
        ull res = 0;
        for(int i=0; i<t.size(); i++){
            res = calc_mod(mul(res, base)+t[i]);
        }
        return res;
    }
    //string s中のtの数をカウント
    inline int count(string t) {
        if(t.size() > n) return 0;
        auto hs = get(t);
        int res = 0;
        for(int i=0; i<n-t.size()+1; i++){
            if(get(i, i+t.size()) == hs) res++; 
        }
        return res;
    }

    /* 
        concat 
        @verify https://codeforces.com/problemset/problem/514/C
    */
    inline ull concat(ull h1, ull h2, int h2len){
      return calc_mod(h2 + mul(h1, pow[h2len]));
    }

    // LCPを求める S[a:] T[b:]
    inline int LCP(int a, int b){
        int len = min((int)hash.size()-a, (int)hash.size()-b);
        
        int lb = -1, ub = len;
        while(ub-lb>1){
            int mid = (lb+ub)/2;

            if(get(a, a+mid) == get(b, b+mid)) lb = mid;
            else ub = mid;
        }
        return lb;
    }
};
vector<vector<pair<int, int>>> g(101010);
int depth[101010];
double p; 
double dfs(int v, int par, int d) {
  double sum = 0.0;
  depth[v] = d;
  for(auto [u, c]: g[v]) {
    if(u == par) continue;
    sum += p * (c+dfs(u, v, d+1));
  }
  return sum;
}
double mypow[101010];
int main() {  
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(12);
  
  cin >> p;
  int n; cin >> n;
  REP(i,n-1) {
    int a, b, c; cin >> a >> b >> c;
    a--; b--;
    g[a].push_back({b, c});
    g[b].push_back({a, c});
  }
  double tmp = dfs(0, -1, 0);
  mypow[0] = 1;
  REP(i,100010) mypow[i+1] = mypow[i] * p;

  double sum = tmp;
  REP(i,n) sum += mypow[depth[i]] * tmp;
  cout << sum << endl;
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 15944
final_rank: 2

code_snippet: #include<bits/stdc++.h>
#pragma GCC optimize("Ofast")
//#pragma GCC target("avx2")
#pragma GCC optimize("unroll-loops")
using namespace std;
//#include<boost/multiprecision/cpp_int.hpp>
//#include<boost/multiprecision/cpp_dec_float.hpp>
//namespace mp=boost::multiprecision;
//#define mulint mp::cpp_int
//#define mulfloat mp::cpp_dec_float_100
struct __INIT{__INIT(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(15);}} __init;
#define INF (1<<30)
#define LINF (lint)(1LL<<56)
#define endl "\n"
#define rep(i,n) for(lint (i)=0;(i)<(n);(i)++)
#define reprev(i,n) for(lint (i)=(n-1);(i)>=0;(i)--)
#define flc(x) __builtin_popcountll(x)
#define pint pair<int,int>
#define pdouble pair<double,double>
#define plint pair<lint,lint>
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define vec vector<lint>
#define nep(x) next_permutation(all(x))
typedef long long lint;
int dx[8]={1,1,0,-1,-1,-1,0,1};
int dy[8]={0,1,1,1,0,-1,-1,-1};
const int MAX_N=4e5+5;
template<class T>bool chmax(T &a,const T &b){if(a<b){a=b;return 1;}return 0;}
template<class T>bool chmin(T &a,const T &b){if(b<a){a=b;return 1;}return 0;}
//vector<int> bucket[MAX_N/1000];
constexpr int MOD=1000000007;
//constexpr int MOD=998244353;
/*#include<atcoder/all>
using namespace atcoder;
typedef __int128_t llint;*/

vector<pair<int,double>> edge[100050];
bool reach[100050];
double rec[100050];
int dep[100050];
double p;

double dfs(int now,int depth,double par){
    if(reach[now]) return rec[now];
    reach[now]=true;
    dep[now]=depth;
    double ret=0;
    ret+=par*p;
    //cout << now << " " << ret << endl;
    rep(i,edge[now].size()){
        if(reach[edge[now][i].fi]) continue;
        ret+=dfs(edge[now][i].fi,depth+1,edge[now][i].se)*p;
    }
    return rec[now]=ret;
}

int main(void){
    cin >> p;
    int N;
    cin >> N;
    rep(i,N-1){
        int u,v;
        double c;
        cin >> u >> v >> c;
        u--,v--;
        edge[u].push_back({v,c});
        edge[v].push_back({u,c});
    }
    double res=dfs(0,1,0);
    double s=res;
    rep(i,N){
        res+=s*pow(p,dep[i]-1);
    }
    cout << res/p << endl;
}
accuracy: 1
time_ms: 30
memory_kb: 18536
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long int;
using ull = unsigned long long int;
using P = pair<int, int>;

double p, z = 0;
vector<vector<P> > g;

double dfs(int now, int pre){
    double res = 0;
    for(auto e : g[now]){
        int nxt = e.first, c = e.second;
        if(nxt == pre) continue;
        res += p*(dfs(nxt,now)+c);
    }
    return res + z;
}

bool solve(){
    int n;
    cin >> p >> n;
    g.resize(n);
    for(int i=0;i<n-1;i++){
        int x, y, c;
        cin >> x >> y >> c;
        x--; y--;
        g[x].push_back(P(y,c));
        g[y].push_back(P(x,c));
    }
    z = dfs(0,-1);
    printf("%.9lf\n",dfs(0,-1));
    return true;
}

int main(){
    solve();
    return 0;
}
accuracy: 1
time_ms: 70
memory_kb: 14500
final_rank: 6

code_snippet: #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
using PII = pair<ll, ll>;
#define FOR(i,a,n) for(ll i=(ll)a; i<(ll)n; ++i)
#define REP(i,n) FOR(i,0,n)

int main() {
	double p;
	ll n;
	cin >> p >> n;
	vector<vector<PII>> g(n);
	REP(i, n - 1) {
		ll a, b, c;
		cin >> a >> b >> c;
		a--, b--;
		g[a].push_back({ b, c });
		g[b].push_back({ a, c });
	}

	double all = 0;
	function<void(ll, ll, double)> pre = [&](ll v, ll par, double prob) {
		for (auto to : g[v]) {
			if (to.first == par) continue;
			all += prob * to.second;
			pre(to.first, v, prob * p);
		}
	};
	pre(0, -1, p);

	double ans = 0;
	function<void(ll, ll, double)> dfs = [&](ll v, ll par, double prob) {
		ans += prob * all;
		for (auto to : g[v]) {
			if (to.first == par) continue;
			ans += prob * p * to.second;
			dfs(to.first, v, prob*p);
		}
	};
	dfs(0, -1, 1);
	
	cout << fixed << setprecision(9) << ans << endl;
}
accuracy: 1
time_ms: 70
memory_kb: 19240
final_rank: 10

code_snippet: #define _USE_MATH_DEFINES

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>

using namespace std;

typedef pair<long long int, long long int> P;

long long int INF = 1e18;
long long int MOD = 1e9 + 7;

vector<int> E[110000];
double p;
double prob[110000] = {};
long long int cost[110000] = {};

void func(int pos, int pre, double pp){
    prob[pos] = pp;
    for(int i = 0; i < E[pos].size(); i++){
        if(E[pos][i] != pre){
            func(E[pos][i], pos, pp * p);
        }
    }
}

int main(){
    cin >> p;
    int N;
    cin >> N;
    for(int i = 0; i < N - 1; i++){
        int u1, u2, c;
        cin >> u1 >> u2 >> c;
        E[u1].push_back(u2);
        E[u2].push_back(u1);
        cost[u2] = c;
    }
    func(1, -1, 1);
    double ans = 0;
    double S = 0;
    for(int i = 1; i <= N; i++){
        ans += prob[i] * cost[i];
        S += prob[i];
    }
    ans += S * ans;
    printf("%.10f\n", ans);
    return 0;
}
accuracy: 0.15789473684210525
time_ms: 60
memory_kb: 16716
final_rank: 20

code_snippet: #define _USE_MATH_DEFINES

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>

using namespace std;

typedef pair<long long int, long long int> P;

long long int INF = 1e18;
long long int MOD = 1e9 + 7;

vector<int> E[110000];
double p;
double prob[110000] = {};
long long int cost[110000] = {};

void func(int pos, double pp){
    prob[pos] = pp;
    for(int i = 0; i < E[pos].size(); i++){
        func(E[pos][i], pp * p);
    }
}

int main(){
    cin >> p;
    int N;
    cin >> N;
    for(int i = 0; i < N - 1; i++){
        int u1, u2, c;
        cin >> u1 >> u2 >> c;
        E[u1].push_back(u2);
        cost[u2] = c;
    }
    func(1, 1);
    double ans = 0;
    double S = 0;
    for(int i = 1; i <= N; i++){
        ans += prob[i] * cost[i];
        S += prob[i];
    }
    ans += S * ans;
    printf("%.10f\n", ans);
    return 0;
}
accuracy: 0.15789473684210525
time_ms: 60
memory_kb: 15252
final_rank: 16

code_snippet: /*  -*- coding: utf-8 -*-
 *
 * 2807.cc: Fractal Tree
 */

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#include<complex>
#include<functional>
 
using namespace std;

/* constant */

const int MAX_N = 100000;

/* typedef */

typedef pair<int,int> pii;
typedef vector<pii> vpii;

struct Stat {
  int i, prt;
  double p;
  Stat() {}
  Stat(int _i, int _prt, double _p): i(_i), prt(_prt), p(_p) {}
};

/* global variables */

vpii nbrs[MAX_N];

/* subroutines */

/* main */

int main() {
  double p;
  int n;
  scanf("%lf%d", &p, &n);

  for (int i = 1; i < n; i++) {
    int x, y, c;
    scanf("%d%d%d", &x, &y, &c);
    x--, y--;
    nbrs[x].push_back(pii(y, c));
    nbrs[y].push_back(pii(x, c));
  }

  queue<Stat> q;
  q.push(Stat(0, -1, 1.0));
  double t = 0.0;

  while (! q.empty()) {
    Stat u = q.front(); q.pop();
    vpii nbru = nbrs[u.i];
    double vp = u.p * p;

    for (vpii::iterator vit = nbru.begin(); vit != nbru.end(); vit++) {
      int &vi = vit->first, &vc = vit->second;
      if (vi != u.prt) {
	t += vc * vp;
	q.push(Stat(vi, u.i, vp));
      }
    }
  }
  //printf("t=%lf\n", t);

  q.push(Stat(0, -1, 1.0));
  double ans = t;
  
  while (! q.empty()) {
    Stat u = q.front(); q.pop();
    vpii nbru = nbrs[u.i];
    double vp = u.p * p;
    ans += t * u.p;

    for (vpii::iterator vit = nbru.begin(); vit != nbru.end(); vit++) {
      int &vi = vit->first;
      if (vi != u.prt)
	q.push(Stat(vi, u.i, vp));
    }
  }
  printf("%.10lf\n", ans);

  return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 9268
final_rank: 1

code_snippet: #include "bits/stdc++.h"
using namespace std;

vector<pair<int,double> > G[100000];
double p;
int n;
int deep=0;
double ans=0;
double ans2;

vector<int> used(100000,0);
vector<int> used1(100000,0);

void dfs(int x){

  deep++;
  for(int i=0;i<G[x].size();i++){
    if(used[G[x][i].first]==0){
      used[G[x][i].first]=1;
      ans+=pow(p,deep)*G[x][i].second;
      dfs(G[x][i].first);
    }
  }
  deep--;
}

void dfs2(int x){
  deep++;
  for(int i=0;i<G[x].size();i++){
    if(used1[G[x][i].first]==0){
      used1[G[x][i].first]=1;
      ans2+=pow(p,deep)*(G[x][i].second+ans);
      dfs2(G[x][i].first);
    }
  }
  deep--;
}

int main(){
  cin>>p>>n;
  for(int i=0;i<n-1;i++){
    int a,b;
    double c;
    cin>>a>>b>>c;
    a--;
    b--;
    G[a].push_back(make_pair(b,c));
    G[b].push_back(make_pair(a,c));
  }
  used[0]=1;
  used1[0]=1;
  dfs(0);
  ans2=ans;
  deep=0;
  dfs2(0);

  cout<< fixed << setprecision(10) <<ans2<<endl;
}
accuracy: 1
time_ms: 110
memory_kb: 15592
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;
using P = pair<int, int>;

vector<bool> used;
vector<vector<P>> g;
vector<P> num;

void dfs(int s, int dep) {
    for (auto&& p : g[s]) {
        int v, c; tie(v, c) = p;
        if (used[v]) continue;
        used[v] = true;
        num[v] = {dep + 1, c};
        dfs(v, dep + 1);
    }
}

int main() {
    double p; cin >> p;
    int N; cin >> N;
    g = vector<vector<P>>(N);
    for (int i = 0; i < N-1; ++i) {
        int x, y, c; cin >> x >> y >> c; --x; --y;
        g[x].push_back({y, c});
        g[y].push_back({x, c});
    }
    used = vector<bool>(N, false);
    num = vector<P>(N, {0, 0});
    used[0] = true;
    dfs(0, 0);

    double t = 0;
    for (int i = 1; i < N; ++i) t += pow(p, num[i].first) * num[i].second;
    double d = 0;
    for (int i = 0; i < N; ++i) d += pow(p, num[i].first);

    cout << fixed << setprecision(7) << t + t * d << endl; 
}
accuracy: 1
time_ms: 90
memory_kb: 12364
final_rank: 7

code_snippet: #include "bits/stdc++.h"
using namespace std;

vector<pair<int,double> > G[100000];
double p;
int n;
int deep=0;
double ans=0;
double ans2;

void dfs(int x){
  deep++;
  for(int i=0;i<G[x].size();i++){
    ans+=pow(p,deep)*G[x][i].second;
    dfs(G[x][i].first);
  }
  deep--;
}

void dfs2(int x){
  deep++;
  for(int i=0;i<G[x].size();i++){
    ans2+=pow(p,deep)*(G[x][i].second+ans);
    dfs2(G[x][i].first);
  }
  deep--;
}

int main(){
  cin>>p>>n;
  for(int i=0;i<n-1;i++){
    int a,b;
    double c;
    cin>>a>>b>>c;
    a--;
    b--;
    if(a>b){
      int tmp=a;
      a=b;
      b=tmp;
    }
    G[a].push_back(make_pair(b,c));
  }
  dfs(0);
  ans2=ans;
  deep=0;
  dfs2(0);

  cout<< fixed << setprecision(10) <<ans2<<endl;

}
accuracy: 0.15789473684210525
time_ms: 80
memory_kb: 11968
final_rank: 18

code_snippet: #include "bits/stdc++.h"
using namespace std;

vector<pair<int,double> > G[100000];
double p;
int n;
int deep=0;
double ans=0;
double ans2;

void dfs(int x){
  deep++;
  for(int i=0;i<G[x].size();i++){
    ans+=pow(p,deep)*G[x][i].second;
    dfs(G[x][i].first);
  }
  deep--;
}

void dfs2(int x){
  deep++;
  for(int i=0;i<G[x].size();i++){
    ans2+=pow(p,deep)*(G[x][i].second+ans);
    dfs2(G[x][i].first);
  }
  deep--;
}

int main(){
  cin>>p>>n;
  for(int i=0;i<n-1;i++){
    int a,b;
    double c;
    cin>>a>>b>>c;
    a--;
    b--;
    int ma,mi;
    ma=max(a,b);
    mi=min(a,b);
    a=mi;
    b=ma;
    G[a].push_back(make_pair(b,c));
  }
  dfs(0);
  ans2=ans;
  deep=0;
  dfs2(0);

  cout<< fixed << setprecision(10) <<ans2<<endl;

}
accuracy: 0.15789473684210525
time_ms: 80
memory_kb: 11988
final_rank: 19

code_snippet: #include "bits/stdc++.h"
using namespace std;

vector<pair<int,int> > G[100000];
double p;
int n;
int deep=0;
double ans=0;
double ans2;

void dfs(int x){
  deep++;
  for(int i=0;i<G[x].size();i++){
    ans+=pow(p,deep)*G[x][i].second;
    dfs(G[x][i].first);
  }
  deep--;
}

void dfs2(int x){
  deep++;
  for(int i=0;i<G[x].size();i++){
    ans2+=pow(p,deep)*(G[x][i].second+ans);
    dfs2(G[x][i].first);
  }
  deep--;
}

int main(){
  cin>>p>>n;
  for(int i=0;i<n-1;i++){
    int a,b,c;
    cin>>a>>b>>c;
    a--;
    b--;
    int ma,mi;
    ma=max(a,b);
    mi=min(a,b);
    a=mi;
    b=ma;
    G[a].push_back(make_pair(b,c));
  }
  dfs(0);
  ans2=ans;
  deep=0;
  dfs2(0);

  cout<< fixed << setprecision(10) <<ans2<<endl;

}
accuracy: 0.15789473684210525
time_ms: 70
memory_kb: 12044
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using P = pair<int, int>;

int main() {
    double p; cin >> p;
    int N; cin >> N;
    auto xy = vector<P>(N-1);
    auto c = vector<int>(N-1);
    for (int i = 0; i < N-1; ++i) {
        cin >> xy[i].first >> xy[i].second >> c[i];
        --xy[i].first; --xy[i].second;
    }
    sort(begin(xy), end(xy));
    auto num = vector<P>(N, {0, 0});
    num[0] = {0, 0};
    for (int i = 0; i < N-1; ++i) {
        num[xy[i].second] = {num[xy[i].first].first + 1, c[i]};
    }
    double t = 0;
    for (int i = 1; i < N; ++i) t += pow(p, num[i].first) * num[i].second;
    double d = 0;
    for (int i = 0; i < N; ++i) d += pow(p, num[i].first);

    cout << fixed << setprecision(7) << t + t * d << endl; 
}
accuracy: 0.15789473684210525
time_ms: 80
memory_kb: 5260
final_rank: 14

code_snippet: #include "bits/stdc++.h"
using namespace std;

vector<pair<int,int> > G[100000];
double p;
int n;
int deep=0;
double ans=0;
double ans2;

void dfs(int x){
  for(int i=0;i<G[x].size();i++){
    deep++;
    ans+=pow(p,deep)*G[x][i].second;
    dfs(G[x][i].first);
    deep--;
  }
}

void dfs2(int x){
  for(int i=0;i<G[x].size();i++){
    deep++;
    ans2+=pow(p,deep)*(G[x][i].second+ans);
    dfs2(G[x][i].first);
    deep--;
  }
}

int main(){
  cin>>p>>n;
  for(int i=0;i<n-1;i++){
    int a,b,c;
    cin>>a>>b>>c;
    a--;
    b--;
    int ma,mi;
    ma=max(a,b);
    mi=min(a,b);
    a=mi;
    b=ma;
    G[a].push_back(make_pair(b,c));
  }
  dfs(0);
  ans2=ans;
  deep=0;
  dfs2(0);

  cout<< fixed << setprecision(10) <<ans2<<endl;

}
accuracy: 0.15789473684210525
time_ms: 80
memory_kb: 11920
final_rank: 17