Problem C - Distance on Tree
Time Limit:500MS Memory Limit: 65536KB
Total Submit: 38 Accepted: 3 SpecialJudge: No
Description
Give you two integers N and k, denote that:a tree has N nodes, numbered from 0 to N-1, each node i( except 0 ) has an edgewith node i/k ( '/' is the operator of division of integer ), whose length isi. And dis(i,j) means the distance between the node i and node j. Now hasQ queries, for each query, give you a interval [l,r], we want to know the sumof dis(i,j) when l <= i < j <= r
Input
There are multiple test cases.
The first line of each case contains three space separated integers N, k andQ.( 2 <= k <= N <= 10000 , Q <= 10000 )
The next Q lines each line contains two space separated integers Li and Ri.( 0<= Li <= Ri <= N-1 )
It's guaranteed that the sum of N is not larger than 500000 and the sum of Q isnot larger than 500000.
Output
For each query, output the answer in aline.
Sample Input
3 2 3
0 2
1 2
0 0
4 2 3
1 2
1 3
0 3
Sample Output
6
2
0
2
10
18
Hint
Please pay attention to the speed ofI/O
Source
解题思路:求sum时,可以将原数组A1.....An从小到大排序,因为序列顺序与结果无关,那么只要在排序好后的数中取出连续的m个数,这m个数的sum最小,那么就是答案,在求sum时,也可以找到规律。
代码如下:
#include<cstdio>
#include<algorithm>
using namespace std;
int s[100005];
int main()
{
int n,m,i,k,j;
long long ans,sum;
while(~scanf("%d%d",&n,&m))
{
for(i=1;i<=n;i++)
scanf("%d",&s[i]);
sort(s+1,s+n+1);
ans=0x3f3f3f3f3f;
if(m==1){
printf("0\n");
continue;
}
for(i=1;i<=n-m+1;i++)
{
sum=0;
for(j=1;j<=m;j++)
sum+=(2*j-m-1)*s[i+j-1];//前j-1作减数,后m-j做被减数,所以(j-1)-(m-j)
if(sum<ans)
ans=sum;
}
printf("%lld\n",ans);
}
return 0;
}