-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplitwiseMinTransactionsDetail.cpp
80 lines (64 loc) · 1.72 KB
/
splitwiseMinTransactionsDetail.cpp
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
78
79
80
#include<iostream>
#include<set>
#include<map>
using namespace std;
//Splitwise Algorithm Implementation
class person_compare{
public:
bool operator()(pair<string, int> p1, pair<string, int> p2){
return p1.second < p2.second;
}
};
int main(){
int no_of_transactions, friends;
cin>>no_of_transactions>>friends;
// person x gives amt to person y
string x,y;
int amt;
// (person: net amount) hashmap
map<string, int> net;
while(no_of_transactions--){
cin>>x>>y>>amt;
if (net.count(x)==0){
net[x]=0;
}
if (net.count(y)==0){
net[y]=0;
}
net[x] -= amt;
net[y] += amt;
}
//List of (Person:net amount) sorted wrt net amount
multiset<pair<string, int>, person_compare> m;
for (auto p:net){
string person = p.first;
int amt = p.second;
if (net[person]!=0){
m.insert(make_pair(person, amt));
}
}
// Make Settlements
int count=0;
while(!m.empty()){
auto low = m.begin();
auto high = prev(m.end());
int debit = low->second;
string debit_person = low->first;
int credit = high->second;
string credit_person = high->first;
m.erase(low);
m.erase(high);
int settled_amt = min(-debit, credit);
count++;
debit += settled_amt;
credit -= settled_amt;
cout<<debit_person<<" will pay "<<settled_amt<<" to "<<credit_person<<endl;
if(debit!=0){
m.insert(make_pair(debit_person, debit));
}
if(credit!=0){
m.insert(make_pair(credit_person, credit));
}
}
cout<<"Minimum Transactions:"<<count;
}