Whuoj-1603

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值