如果能想到二分求解,这道题目基本就能过了,我说一个坑了我很久的细节吧
long long res[maxn],an[maxn];
int mid,i;
res[i]=an[i]+mid*i;
res[i]=an[i]+(long long) (mid*i);
res[i]=an[i]+(long long)mid*i;
这三种写法看起来很相似,但是当mid*i>int的最大值时,会有不同结果,第一种写法对于mid*i(它们乘积也是一个int类型的)超过int会得到一个算是随机的数字导致答案错误,第二种写法是在mid*i超出int之后才改变的类型,没什么用,第三种是正解,强制类型转换mid之后,因为*左右类型不同所以向位数更多的类型转换(应该是这样)
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys kitems with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.
Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?
The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs.
On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these ksouvenirs.
3 11 2 3 5
2 11
4 100 1 2 5 6
4 54
1 7 7
0 0
In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items.
In the second example, he can buy all items as they will cost him [5, 10, 17, 22].
In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it.
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define maxn 100005
using namespace std;
long long an[maxn],res[maxn];
int main()
{
int n,s,l,r,ans=0;
scanf("%d%d",&n,&s);
for(int i=1;i<=n;i++)
{
scanf("%lld",&an[i]);
}
l=1,r=n;
while(r>=l)
{
int mid=(l+r)>>1;
for(int i=1;i<=n;i++)
{
res[i]=an[i]+(long long)mid*i;
}
sort(res+1,res+n+1);
long long sum=0;
for(int i=1;i<=mid;i++)
{
sum+=res[i];
}
if(sum<=s)
{
ans=mid;
l=mid+1;
}
else
r=mid-1;
}
if(ans)
{
for(int i=1;i<=n;i++)
{
res[i]=an[i]+(long long)ans*i;
}
sort(res+1,res+n+1);
long long sum=0;
for(int i=1;i<=ans;i++)
{
sum+=res[i];
}
printf("%d %lld",ans,sum);
}
else
printf("0 0");
return 0;
}