Skip to content

Commit ffa30db

Browse files
authored
Create TheSplitwiseProblem.cpp
1 parent 36e9a1d commit ffa30db

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
const int N = 1e6;
4+
int balance[N];
5+
int main()
6+
{
7+
int i, n, m, u, v, w, poor, x, rich, y;
8+
cin >> n >> m;
9+
for(i=0; i<m; i++) {
10+
cin >> u >> v >> w;
11+
//u has to pay v an amount w
12+
balance[u] -= w;
13+
balance[v] += w;
14+
}
15+
16+
multiset<tuple<int,int>> S;
17+
for(i=0; i<n; i++)
18+
if(balance[i] != 0) S.insert(make_tuple(balance[i], i));
19+
20+
int count = 0;
21+
while(!S.empty()) {
22+
tie(poor, x) = *S.begin(); S.erase(S.begin());
23+
tie(rich, y) = *S.rbegin(); S.erase(prev(S.end()));
24+
int amount = min(-poor, rich);
25+
26+
count++; //poor pays amount "amount" to rich
27+
printf("%d pays %d amount to %d\n", x, amount, y);
28+
poor += amount;
29+
rich -= amount;
30+
31+
if (poor) S.insert(make_tuple(poor, x));
32+
if (rich) S.insert(make_tuple(rich, y)~);
33+
}
34+
35+
cout << count << endl;
36+
37+
38+
}

0 commit comments

Comments
 (0)