二分法——洗衣服程式碼暫時存
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int n, k;
long long a[100006];
long long obj = 0;
void add(int h)
{
for (int i = 0; i<n; i++)
{
if (i != h)
a[i]--;
obj = a[i];
}
}
int solve(long long t)
{
long long t1 = 0;
long long time = t;
for (int i = n - 1; i >= 0; i--)
{
while (a[i]>time)
{
a[i] -= k;
obj = a[i];
t1++;
add(i);
time = t - t1;
}
}
if (time<0)
return -1;//說明時間短了,需要的時間比t多
else if (time>0)
return 1;//說明時間長了,需要的時間比t少
else
return 0;//說明時間正好
}
int main()
{
int cas = 1;
while (1)
{
printf("sample input #%d\n", cas);
scanf("%d", &n);
long long maxt = 0;
for (int i = 0; i<n; i++)
{
scanf("%lld", &a[i]);
if(a[i]>maxt)
maxt=a[i];
}
scanf("%d", &k);
sort(a, a + n);
long long mint = 1 ;
long long midt = (mint + maxt) / 2;
while (mint <= maxt)
{
if (solve(midt) == 1)
maxt = midt - 1;
if (solve(midt) ==-1)
mint = midt + 1;
if (solve(midt) == 0)
break;
midt = (mint + maxt) / 2;
}
printf("sample output #%d\n%lld\n", cas, midt);
cas++;
}
return 0;
}