-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathantiBruteForceLock_UVA1235OJ.cpp
100 lines (86 loc) · 1.97 KB
/
antiBruteForceLock_UVA1235OJ.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
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <string>
#include <vector>
using namespace std;
struct edge
{
int u;
int v;
int d;
bool operator < (const edge & temp) const
{
return d < temp.d;
}
};
int _find(int u, vector<int> & p)
{
if (p[u] == u)
{
return u;
}
else
{
int ans = _find(p[u], p);
p[u] = ans;
return ans;
}
}
int rollCount(string key0, string key1)
{
int ans = 0;
for (int i = 0; i <= 3; ++i)
{
ans += min(abs(key0[i] - key1[i]), 10 - abs(key0[i] - key1[i]));
}
return ans;
}
int main()
{
ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
int testCase; cin >> testCase;
for (int c0 = 1; c0 <= testCase; ++c0)
{
int n, minToGet = 36; cin >> n;
vector<string> keys(n);
vector<int> p(n);
vector<edge> ways;
for (int i = 0; i <= n - 1; ++i)
{
cin >> keys[i];
minToGet = min(minToGet, rollCount("0000", keys[i]));
for (int j = 0; j <= i - 1; ++j)
{
edge temp{i, j, rollCount(keys[i], keys[j])};
ways.push_back(temp);
}
}
sort(ways.begin(), ways.end());
for (int i = 0; i <= n - 1; ++i)
{
p[i] = i;
}
int total = 0, sizeWays = ways.size();
for (int i = 0, j = 0; i <= n - 2 && j <= sizeWays - 1; ++j)
{
int res0 = _find(ways[j].u, p), res1 = _find(ways[j].v, p);
if (res0 == res1)
{
continue;
}
p[res0] = p[res1];
total += ways[j].d;
++i;
}
cout << minToGet + total << '\n';
}
cout.flush();
return 0;
}