-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.cpp
More file actions
96 lines (75 loc) · 2.24 KB
/
project.cpp
File metadata and controls
96 lines (75 loc) · 2.24 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* Input */
/* 3 3
Nikki John 100
John Neha 50
Neha Nikki 40 */
/* Output */
/* Nikki will pay 50 to the John
Nikki will pay 10 to the Neha
2 */
#include <iostream>
#include<set>
#include<map> //To store net balance of the person.
using namespace std;
//In this we will also tell about the transaction details.
//eg. A has to give rs. x to B, and so on.
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;
string x,y;
int amount;
map<string,int> net;
while(no_of_transactions--){
cin>>x>>y>>amount;
if(net.count(x)==0){
net[x] = 0;
}
if(net.count(y)==0){
net[y] = 0;
}
net[x] -= amount;
net[y] += amount;
}
multiset<pair<string,int>, person_compare> m;
//Iterate over person, add these in the multiset who have no zero set.
for(auto p:net){
string person = p.first;
int amount = p.second;
if(net[person]!=0){
m.insert(make_pair(person,amount)); //now in multiset the comparisons will be done on the basis of first parameter, so either move amount at the first or make a custom func. to d so.
}
}
//settlements , pop elements from start and end.
int cnt = 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;
//pop them out.
m.erase(low);
m.erase(high);
int settled_amount = min(-debit,credit);
debit += settled_amount;
credit -= settled_amount;
//print transcations.
cout<<debit_person<<" will pay "<<settled_amount<<" to the "<<credit_person<<endl;
if(debit != 0){
m.insert(make_pair(debit_person,debit));
}
if(credit != 0){
m.insert(make_pair(credit_person,credit));
}
cnt += 1;
}
cout<<cnt<<endl;
return 0;
}