-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP11679.cpp
executable file
·114 lines (107 loc) · 2.73 KB
/
P11679.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
int owed[20][20]; // owed[i][j] => Bank i+1 owes i+j amount
int totalOwed[20]; // [i] => Bank i+1 owes in total
int reserves[20];
bool visited[20];
int B;
bool removeCycleDfs(int start, int cur, int &minLink) {
if(cur == start) {
//cerr << "Cycle found from " << start << " of min price " << minLink << endl;
return true;
}
visited[cur] = true;
int oldMinLink = minLink;
FORJ(B) {
if(visited[j])
continue;
minLink = oldMinLink;
if(owed[cur][j] > 0) {
if(owed[cur][j] < minLink)
minLink = owed[cur][j];
if(removeCycleDfs(start, j, minLink)) {
totalOwed[cur] -= minLink;
owed[cur][j] -= minLink;
// Note: Reserves stay unchanged!
visited[cur] = false;
//cerr << " Cycle reduction " << cur << "->" << j << " remaining: " << owed[cur][j] << endl;
return true;
}
}
}
visited[cur] = false;
return false;
}
void removeCyclesFrom(int start) {
FORJ(B) { // Try to find cycles by first going to all neighbours
if(j == start)
continue;
while(owed[start][j] > 0) {
int minLink = owed[start][j];
if(!removeCycleDfs(start, j, minLink))
break;
totalOwed[start] -= minLink;
owed[start][j] -= minLink;
// cerr << " Cycle reduction " << start << "=>" << j << " remaining: " << owed[start][j] << endl;
}
}
}
// OK. So apaprently banks don't need to have money to spend money... confusing problem definition. Ignore the methods above.
int main() {
int N, from, to, amount; // Banks, debentures
while(true) {
cin >> B >> N;
if(B == 0 && N == 0)
return 0;
FORI(B) {
FORJ(B)
owed[i][j] = 0;
totalOwed[i] = 0;
visited[i] = false;
cin >> reserves[i];
}
FORI(N) {
cin >> from >> to >> amount; --from; --to;
if(from == to)
continue;
owed[from][to] += amount;
totalOwed[from] += amount;
reserves[from] -=amount;
reserves[to] += amount;
}
/*
// Remove cycles
FORI(B) {
if(reserves[i] != 0)
removeCyclesFrom(i);
}
// Fix rest greedily:
bool improved = true;
while(improved) {
improved = false;
FORI(B) { // Try to improve all banks
if(reserves[i] == 0 || totalOwed[i] == 0)
continue;
improved = true;
// Try to pay off debt:
FORJ(B && reserves[i] > 0) {
if(owed[i][j] == 0)
continue;
int pay = MIN(owed[i][j], reserves[i]);
owed[i][j] -= pay;
reserves[i] -= pay;
reserves[j] += pay;
totalOwed[i] -= pay;
//cerr << "Normal payment " << i << "->" << j << ": " << pay << ". Remaining: " << owed[i][j] << endl;
} // FORJ
} // FORI
} // while improved
*/
char ret = 'S';
FORI(B) {
if(reserves[i] < 0) {
ret = 'N';
break;
}
}
cout << ret << endl;
} // while true
}