forked from cacophonix/SPOJ
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BOOKS1.cpp
133 lines (103 loc) · 2.48 KB
/
BOOKS1.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
/*
USER: zobayer
TASK: BOOKS1
ALGO: binary search
*/
#include <iostream>
#define M 500
using namespace std;
int p[M+1], a[M+1];
long long search_result(const int& m, const int& n, long long begin_p, long long end_p);
bool feasible(const int& m, const int& n, const long long& thre);
void print_result(const int& m, const int& n, const long long& thre);
int main()
{
int num_of_cases;
long long sum, avg, max_value, thre;
cin >> num_of_cases;
for(int counter = 0; counter < num_of_cases; counter++)
{
int m, n;
cin >> m >> n;
a[0] = sum = max_value = 0;
for(int i = 1; i <= m; i++)
{
cin >> p[i];
max_value = ((max_value > p[i])? max_value : p[i]);
sum += p[i];
a[i] = a[i-1] + p[i];
}
avg = sum / n;
avg = ((avg > max_value)? avg : max_value);
thre = search_result(m, n, avg, sum);
print_result(m, n, thre);
}
return 0;
}
long long search_result(const int& m, const int& n, long long begin_p, long long end_p)
{
long long temp;
while(begin_p < end_p)
{
temp = (begin_p + end_p) / 2;
if(feasible(m, n, temp))
end_p = temp;
else
begin_p = temp + 1;
}
return end_p;
}
bool feasible(const int& m, const int& n, const long long& thre)
{
int k = 0;
for(int i = m; i >= 1;)
{
long long temp = 0;
for(int j = i-1; j >= 0; j--)
{
if(a[i] - a[j] > thre)
{
temp = j + 1;
break;
}
}
i = temp, k++;
}
return (k <= n);
}
void print_result(const int& m, const int& n, const long long & thre)
{
int k = 0;
long long temp;
bool seq[m];
for(int i = 0; i < m; i++)
seq[i] = false;
for(int i = m; i >= 1;)
{
temp = 0;
for(int j = i-1; j >= 0; j--)
{
if(a[i] - a[j] > thre)
{
temp = j + 1;
break;
}
}
i = temp, k++;
seq[i] = true;
}
temp = 1;
while(k < n)
{
if(!seq[temp])
seq[temp] = true, k++;
temp++;
}
for(int j = 1; j < m; j++)
{
cout << p[j] << ' ';
if(seq[j])
cout << "/ ";
}
cout << p[m] << endl;
}