-
Notifications
You must be signed in to change notification settings - Fork 34
/
1040-Donation.cpp
155 lines (104 loc) · 1.92 KB
/
1040-Donation.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include <queue>
#include <iostream>
#include <utility>
#include <limits.h>
#include <fstream>
#include <string.h>
#define ii pair <int, int>
#define pii pair <int, ii>
using namespace std;
int count = 0;
int check[100];
int a[100][100];
int test(int i, int n)
{
for (int j = 0; j < n; j++) {
if(i != j and (a[i][j] != INT_MAX or a[j][i] != INT_MAX) and check[j] == 0) {
check[j] = 1;
count++;
test(j, n);
}
}
}
int prim()
{
int ans[100][100];
int already[100];
long long total;
total = 0;
priority_queue < pair<int, ii>, vector <pair < int, ii> >, greater <pair < int, ii> > > q;
int n;
int m;
int x;
int y;
int w;
int n1;
int n2;
int dist = 0;
pair <int, ii> temp;
cin >> n;
m = n * n;
for (int i = 0; i < n; i++) {
already[i] = -1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
total += a[i][j];
ans[i][j] = INT_MAX;
if(a[i][j] == 0) {
a[i][j] = INT_MAX;
}
}
}
+
memset(check, 0, sizeof(check));
count = 1;
check[0] = 1;
test(0, n);
if(count != n) {
return -1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = min(a[i][j], a[j][i]);
}
}
already[0] = 1;
for (int i = 0; i < n; i++) {
q.push(pii (a[0][i],(ii ( 0, i))));
}
for (int j = 1; j < n; j++) {
do
{
temp = q.top();
q.pop();
w = temp.first;
x = temp.second.first;
y = temp.second.second;
} while(already[x] != -1 and already[y] != -1 and !q.empty());
ans[x][y] = w;
dist += w;
if(already[x] == -1) {
for (int i = 0; i < n; i++) {
q.push(pii(a[x][i], ii(x, i)));
already[x] = 1;
}
}
else {
for (int i = 0; i < n; i++) {
q.push(pii(a[y][i], ii(y, i)));
already[y] = 1;
}
}
}
return (total - dist);
}
int main()
{
int t;
scanf("%d", &t);
for (int cases = 1; cases <= t; cases++) {
printf("Case %d: %d\n", cases, prim());
}
}