-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSSORT(spoj).cpp
66 lines (60 loc) · 1.55 KB
/
SSORT(spoj).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
#include<bits/stdc++.h>
using namespace std;
int a[100000];
int b[100000];
bool vis[100000];
int main()
{
int N;
int t = 0;
while (scanf("%d", &N) && N)
{
t++;
for (int i = 0; i < N; ++i)
{
scanf("%d", &a[i]);
b[i] = a[i];
vis[i] = false;
}
sort(b, b + N);
map<int, int> place;
for (int i = 0; i < N; ++i)
place[b[i]] = i;
int res = 0;
for (int i = 0; i < N; ++i)
{
if (vis[i] == false)
{
if (place[a[i]] == i)
{
vis[i] = true;
continue;
}
// We're in new cycle
int min_val = a[i];
int num = 0;
int sum = 0;
int j = i;
while (vis[j] == false)
{
sum += a[j];
num++;
if (a[j] < min_val)
{
min_val = a[j];
}
vis[j] = true;
j = place[a[j]];
}
sum -= min_val;
res += sum + min_val * (num - 1);
if (2 * (b[0] + min_val) <(min_val - b[0]) * (num - 1))
{
res -= (min_val - b[0]) * (num - 1) - 2 * (b[0] + min_val);
}
}
}
printf("Case %d: %d\n\n", t, res);
}
return 0;
}