书的复制
2024年12月25日大约 2 分钟
枚举
#include <bits/stdc++.h>
using namespace std;
int m, k;
int a[505];
bool check(int x)
{
int cnt = 0; // 需要几个人
int now = 0; // 当前这个人花的时间
for (int i = 1; i <= m; i++)
{
// 这一本书 x 都抄不完
if (a[i] > x)
return false;
// 看看前一个人能不能再抄一本书
if (now + a[i] > x)
{
cnt++;
now = a[i];
}
else
now += a[i];
}
if (now > 0)
cnt++;
return cnt <= k;
}
struct Plan
{
int l, r, tim;
};
vector<Plan> plan;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> m >> k;
for (int i = 1; i <= m; i++)
cin >> a[i];
// # 找到最少时间
// 枚举每个人花费不超过多少时间
int ans = 0;
for (int i = 1;; i++)
{
if (check(i))
{
ans = i;
break;
}
}
// cout << ans << "\n";
// # 根据最少时间生成方案
int last = m;
int now = 0;
for (int i = m; i >= 1; i--)
{
if (now + a[i] <= ans)
now += a[i];
else
{
plan.push_back((Plan){i + 1, last, now});
now = a[i];
last = i;
}
}
plan.push_back((Plan){1, last, now});
for (int i = (int)plan.size() - 1; i >= 0; i--)
cout << plan[i].l << " " << plan[i].r << "\n";
return 0;
}
二分
#include <bits/stdc++.h>
using namespace std;
int m, k;
int a[505];
bool check(int x)
{
int cnt = 0; // 需要几个人
int now = 0; // 当前这个人花的时间
for (int i = 1; i <= m; i++)
{
// 这一本书 x 都抄不完
if (a[i] > x)
return false;
// 看看前一个人能不能再抄一本书
if (now + a[i] > x)
{
cnt++;
now = a[i];
}
else
now += a[i];
}
if (now > 0)
cnt++;
return cnt <= k;
}
struct Plan
{
int l, r, tim;
};
vector<Plan> plan;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> m >> k;
for (int i = 1; i <= m; i++)
cin >> a[i];
// # 找到最少时间
// 枚举每个人花费不超过多少时间
int ans = 0;
int l = 1;
int r = 1000000000;
while (l <= r)
{
int mid = (l + r) / 2;
if (check(mid))
{
ans = mid;
r = mid - 1;
}
else
l = mid + 1;
}
// cout << ans << "\n";
// # 根据最少时间生成方案
int last = m;
int now = 0;
for (int i = m; i >= 1; i--)
{
if (now + a[i] <= ans)
now += a[i];
else
{
plan.push_back((Plan){i + 1, last, now});
now = a[i];
last = i;
}
}
plan.push_back((Plan){1, last, now});
for (int i = (int)plan.size() - 1; i >= 0; i--)
cout << plan[i].l << " " << plan[i].r << "\n";
return 0;
}