forked from sitz/UVa-Online-Judge
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1016.cpp
52 lines (47 loc) · 905 Bytes
/
1016.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
#include <bits/stdc++.h>
using namespace std;
const int NN = 1024;
#define FOR(i, n) for (int i = 0; i < n; ++i)
int pos[NN], v[NN], v2[NN];
int main()
{
for (int n, T = 1; scanf("%d", &n) == 1 && n; ++T)
{
FOR(i, n)
scanf("%d", v + i), pos[v[i]] = i, v2[i] = v[i];
sort(v2, v2 + n);
int cost = 0, swapper = v2[0];
FOR(i, n)
{
int idx = -1, steps = 0, z = NN;
FOR(j, n)
if (v[j] != v2[j] && v[j] < z)
{
idx = j, z = v[j];
}
if (idx == -1)
{
break;
}
while (v[idx] != v2[idx])
{
z = pos[v2[idx]];
cost += v[z];
swap(v[z], v[idx]);
swap(pos[v2[idx]], pos[v[idx]]);
idx = pos[v[idx]];
++steps;
}
if (steps * (v[idx] - swapper) < 2 * (v[idx] + swapper))
{
cost += v[idx] * steps;
}
else
{
cost += 2 * (v[idx] + swapper) + swapper * steps;
}
}
printf("Case %d: %d\n\n", T, cost);
}
return 0;
}