P7113 排水系统
AAA_Chris_123 · · 算法·理论
P7113 排水系统
题意分析
给你一个有向无环图,“根”的权值为1,每个点的点权会平均地分配给每个“儿子”,问所有“叶子”的最简分数形式下的权值。
算法简介
既然给了个
记
我们再看一眼数据范围,发现
所以分母上限为:__int128。
其实这题可能有另一种做法:
注意到
我们就能把每个点的权值转化为:
到叶子时把值记录下来,最后统一通分相加即可。
赛时代码
注意到我是
#include <bits/stdc++.h>
#define int long long
using namespace std;
struct Edge { int from, to; };
struct Calc {
__int128 x, y; int Top, St[100];
Calc() { x = 0, y = 1; }
__int128 gcd(__int128 A, __int128 B) { return B ? gcd(B, A % B) : A; }
Calc GetAns(Calc _) {
__int128 G = gcd(_.x, _.y);
Calc Res; Res.x = _.x / G; Res.y = _.y / G;
return Res;
}
Calc operator * (Calc _) {
Calc Res; Res.x = x * _.x; Res.y = y * _.y;
return GetAns(Res);
}
Calc operator + (Calc _) {
Calc Res; Res.x = x * _.y + y * _.x; Res.y = y * _.y;
return GetAns(Res);
}
void Print() {
while(x) {
St[++Top] = x % 10;
x /= 10;
}
while(Top) cout << St[Top--];
cout << " ";
while(y) {
St[++Top] = y % 10;
y /= 10;
}
while(Top) cout << St[Top--];
cout << '\n';
}
};
const int N = 1e5 + 5;
int n, m;
vector<int> V;
int Indegree[N], Siz[N];
Calc Data[N];
int Cur, Head[N], Next[N << 3]; Edge G[N << 3];
void EdgeInit() { Cur = 0; for(int i = 1; i <= n; i++) Head[i] = -1; }
void AddEdge(int x, int y) { G[++Cur] = {x, y}; Next[Cur] = Head[x]; Head[x] = Cur; }
void Topo() {
queue<int> Q;
for(int i = 1; i <= m; i++) { Data[i].x = Data[i].y = 1; Q.push(i); }
while(!Q.empty()) {
int x = Q.front(); Q.pop();
if(!Siz[x]) continue;
Calc Value; Value.x = 1; Value.y = Siz[x];
Value = Data[x] * Value;
for(int i = Head[x]; ~i; i = Next[i]) { int y = G[i].to;
Data[y] = Data[y] + Value;
if(!--Indegree[y]) Q.push(y);
}
}
}
void Main() {
cin >> n >> m; EdgeInit();
for(int x = 1; x <= n; x++) {
cin >> Siz[x]; if(!Siz[x]) V.push_back(x);
for(int i = 1; i <= Siz[x]; i++) {
int y; cin >> y;
AddEdge(x, y); Indegree[y]++;
}
}
Topo();
for(int i = 0; i < V.size(); i++) Data[V[i]].Print();
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
Main(); return 0;
}
::::