Existing \ (n-\) individuals with \ (m \) of debt relationship: \ (D (A, B) \) represents \ (A \) under \ (b \ d (a, b) \) Element . Now we are given a final debt relationship, such that \ (\ sum d \) minimum.
Solution
Only needs to record the total amount of each of the input and output points, each into a negative, positive and negative portion toward the portion to do a similar operation can be matched
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1000005;
struct item {int a,b,c;};
int n,m,u,v,w,d[N];
signed main() {
ios::sync_with_stdio(false);
cin>>n>>m;
for(int i=1;i<=m;i++) {
cin>>u>>v>>w;
d[u]-=w;
d[v]+=w;
}
int pos=1;
vector <item> vec;
for(int i=1;i<=n;i++) {
while(d[i]>0) {
while(d[pos]>=0&&pos<=n) ++pos;
int tmp=min(-d[pos],d[i]);
d[pos]+=tmp;
d[i]-=tmp;
vec.push_back({pos,i,tmp});
}
}
cout<<vec.size()<<endl;
for(item i:vec) cout<<i.a<<" "<<i.b<<" "<<i.c<<endl;
}