0%

P1182 数列分段 Section II

60pts TLE 可能是check函数复杂度太高了

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
#include <iostream>
using namespace std;
typedef long long ll;
const ll maxn=1e5+10,maxans=1e13+7;
ll n,m,a[maxn];
inline bool check(ll x) {
ll s=1,subCnt=0;
while (s<=n) {
ll res=0,cnt=0;
for(ll i=s;i<=n;i++) {
if(res+a[i]>x)
break;
res+=a[i];
cnt+=1;
}
s+=cnt;
subCnt+=1;
}
if(subCnt<=m) {
return true;
}
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++) {
cin>>a[i];
}
ll l=1,r=maxans;
while(l<r) {
ll mid=l+r>>1;
if(check(mid)) r=mid;
else l=mid+1;
}
cout<<l<<endl;
return 0;
}
// 60pts https://www.luogu.com.cn/record/180491211

可以二分里套二分,当然那个二分我们就不写了,直接上stl

P1182_2.in

P1182_2.out

不过我仔细分析了一下时间复杂度,以及这个样例(另一道题目https://www.luogu.com.cn/problem/P2884)

1
2
3
4
5
6
7
8
7 5
100
400
300
100
500
101
400
1
500

会使上面这个程序死循环,让我确信不是check()的问题

仔细分析过后,发现还是check()的问题,check死循环了。

1
2
3
4
5
6
7
8
9
10
11
while (s<=n) {
ll res=0,cnt=0;
for(ll i=s;i<=n;i++) {
if(res+a[i]>x) // 某些情况下,cnt走不到cnt+1,导致s停滞不前,导致死循环
break;
res+=a[i];
cnt+=1;
}
s+=cnt;
subCnt+=1;
}

解决起来倒也简单

ll l=maxa,r=maxans;

让左端点比数组中最大的元素大,就可以了,这样可以保证cnt的前进。

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
// https://www.luogu.com.cn/problem/P2884
// https://www.luogu.com.cn/problem/P1182 双倍经验
#include <iostream>
using namespace std;
typedef long long ll;
const ll maxn=1e5+10,maxans=1e13+7;
ll n,m,a[maxn];
inline bool check(ll x) {
ll s=1,subCnt=0;
while (s<=n) {
ll res=0,cnt=0;
for(ll i=s;i<=n;i++) {
if(res+a[i]>x)
break;
res+=a[i];
cnt+=1;
}
s+=cnt;
subCnt+=1;
}
if(subCnt<=m) {
return true;
}
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n>>m;
ll maxa=0;
for(int i=1;i<=n;i++) {
cin>>a[i],maxa=max(maxa,a[i]);
}
ll l=maxa,r=maxans;
while(l<r) {
ll mid=l+r>>1;
if(check(mid)) r=mid;
else l=mid+1;
}
cout<<l<<endl;
return 0;
}
// 60pts TLE https://www.luogu.com.cn/record/180491211
// 40pts TLE https://www.luogu.com.cn/record/180498527
// AC https://www.luogu.com.cn/record/180509878
// AC https://www.luogu.com.cn/record/180510298