-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplitwise.cpp
More file actions
77 lines (67 loc) · 1.73 KB
/
Copy pathsplitwise.cpp
File metadata and controls
77 lines (67 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <stack>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
#include <sstream>
#include <iomanip>
using namespace std;
int32_t main()
{
int no_transactions, friends;
cin >> no_transactions >> friends;
int x, y, amount;
// A one dimentional array to store the net amount that each person will have to take at the end
vector<int> net(100000, 0);
while (no_transactions)
{
cin >> x >> y >> amount;
net[x] -= amount;
net[y] += amount;
}
//Using multiset so that we can have multiple equal values in a sorted order
multiset<int> m;
for (int i = 0; i < friends; i++)
{
if (net[i])
m.insert(net[i]);
}
int count = 0;
while (!m.empty())
{
auto low = m.begin();
auto high = prev(m.end());
//pop out two elements from start and end as they would be the max credit and max credit
int debit = *low;
int credit = *high;
m.erase(low);
m.erase(high);
int settlement_amount = min(-debit, credit);
count++;
//Settlement
debit += settlement_amount;
credit -= settlement_amount;
//The remainder of the settlement is pushed back into the multiset
if(credit)
m.insert(credit);
if(debit)
m.insert(debit);
}
cout<<"Total number of transactions required at the end : "<<count<<endl;
}