zoukankan      html  css  js  c++  java
  • 数据结构--树状数组(黑龙江省第八届大学生程序设计竞赛--post office)

    例题来源:

    题目:

    1468: Post office


    题目描述

    There are N(N<=1000) villages along a straight road, numbered from 1 to N for simplicity. We know exactly the position of every one (noted pos[i],pos[i] is positive integer and pos[i]<=10^8). The local authority wants to build a post office for the people living in the range i to j(inclusive). He wants to make the sum of |pos[k]-position_of_postoffice| (i<=k<=j) is minimum. 

    输入

      For each test case, the first line is n. Then n integer, representing the position of every village and in acending order. Then a integer q (q<=200000), representing the queries. Following q lines, every line consists of two integers i and j. the input file is end with EOF. Total number of test case is no more than 10.
    Be careful, the position of two villages may be the same.

    输出

      For every query of each test case, you tell the minimum sum.

    样例输入

    3
    1 2 3
    2
    1 3
    2 3
    

    样例输出

    2
    1
    题意:在x轴上按从小到大的顺序给出n个点的坐标,每次询问第i到第j个村庄内,在哪儿建一个post office,使这些村庄到post office的距离和最小。
    思路:很显然,邮局应该建在这j-i+1个村庄的最中间村庄,对区间距离求和我们是有使用快速幂!
    代码如下:
     1 #include "stdio.h"
     2 #include "string.h"
     3 
     4 long long sum[1005];
     5 
     6 long long Low(long long x)  
     7 {
     8     return x&(-x);
     9 }
    10 
    11 long long SUM(long long x) //树状数组求区间和
    12 {
    13     long long ans = 0;
    14     for(long long i=x; i>0; i-=Low(i))
    15         ans += sum[i];
    16     return ans;
    17 }
    18 
    19 int main()
    20 {
    21     long long n;
    22     long long i,j,k;
    23     long long x,y,Q;
    24     long long mid;
    25     while(scanf("%lld",&n)!=EOF)
    26     {
    27         memset(sum,0,sizeof(sum));
    28         for(i=1; i<=n; ++i)
    29         {
    30             scanf("%lld",&k);
    31             for(j=i; j<=n; j += Low(j))
    32                 sum[j] += k;
    33         }
    34         scanf("%lld",&Q);
    35         while(Q--)
    36         {
    37             scanf("%lld %lld",&x,&y);
    38             mid = x+(y-x+1)/2;
    39             if((y-x+1)%2==0)
    40                 printf("%lld
    ",SUM(y)-SUM(mid-1)-(SUM(mid-1)-SUM(x-1)));
    41             else
    42                 printf("%lld
    ",SUM(y)-SUM(mid)-(SUM(mid-1)-SUM(x-1)));
    43         }
    44     }
    45     return 0;
    46 }
  • 相关阅读:
    COCO2018 目标检测
    最小生成树[摘录自严长生老师的网站]
    PANet训练自己的数据(VIA标注)
    图的遍历[摘录自严长生老师的网站]
    图的链式存储(邻接表)【摘录自严长生老师的网站】
    Android写入到mysql里的中文总是乱码?
    Mac 当xampp里mysql无法启动的解决办法
    【代码段】Android Studio使用DatePicker选择日期
    Android jdbc连接mysql报错解决方案 (Communications link failure)
    绝命毒师口语精析(4)
  • 原文地址:https://www.cnblogs.com/ruo-yu/p/4411963.html
Copyright © 2011-2022 走看看