---
id: 621
lang: en
translation_of: index.md
source_sha256: 60f7c91deefb5141da346a60153c0dff79a0ab782a417eb8e6ad4f10327042e2
title: "P4316: The Mung Bean Frog's Destination — Solution"
description: "A pretty good problem (an easy one big shots insta-solve): we run a Topo Sort on the DAG to tally the answer."
tags: []
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 绿豆蛙的归宿 rendered as “The Mung Bean Frog's Destination” (绿豆 is mung bean; 归宿 “final destination”)."
  - "被巨佬秒切的水题 rendered as “an easy problem that big shots insta-solve”; 秒切 chipped as one phrase."
---

## Main Idea

This is a pretty good problem (<span class="slang" data-zh="水题" data-gloss="shuǐtí, “water problem”. An easy problem.">an easy problem</span> that <span class="slang" data-zh="巨佬" data-gloss="jùlǎo, “huge guy”. A very skilled contestant; used with admiration.">big shots</span> <span class="slang" data-zh="秒切" data-gloss="miǎo qiē, “cut in a second”. To solve a problem instantly, almost without thinking.">insta-solve</span>). We run a Topo Sort on the DAG to tally the answer. For node $i$, the probability is

$$
P(i) = \sum_{(u, i)} \frac{P(u)}{outDegree[u]}
$$

So for the expectation, we only need to multiply the probability by the edge's coefficient and accumulate using linearity.

## Code

```cpp
// P4316.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100000 + 100;
int head[MAX_N], current, n, m, tmpx, tmpy, tmpz, indeg[MAX_N], outdeg[MAX_N];
double pro[MAX_N], ans = 0;
struct edge
{
	int to, nxt;
	double weight;
} edges[MAX_N << 1];
void addpath(int u, int v, int w)
{
	edges[current].to = v, edges[current].nxt = head[u];
	edges[current].weight = w, head[u] = current++;
}
void toposort()
{
	queue<int> q;
	q.push(1);
	pro[1] = 1;
	while (!q.empty())
	{
		int pt = q.front();
		q.pop();
		for (int i = head[pt]; i != -1; i = edges[i].nxt)
		{
			int to = edges[i].to;
			ans += (double)(pro[pt] / (double)outdeg[pt] * (double)edges[i].weight);
			pro[to] += (double)(pro[pt] / (double)outdeg[pt]);
			indeg[to]--;
			if (indeg[to] == 0)
				q.push(to);
		}
	}
}
int main()
{
	memset(head, -1, sizeof(head));
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= m; i++)
		scanf("%d%d%d", &tmpx, &tmpy, &tmpz), addpath(tmpx, tmpy, tmpz), indeg[tmpy]++, outdeg[tmpx]++;
	toposort();
	printf("%.2lf", ans);
	return 0;
}
```
