校门外的树"/>
(水题)洛谷P1047 校门外的树
无聊做一下水题,练下线段树
这道题可以暴力模拟做(数组填充), 树状数组, 分块, 线段树, 珂朵莉树。下面采用线段树的方法
题目太水就不做过多解释了
洛谷 P1047 校门外的树
Description
某校大门外长度为L的马路上有一排树,每两棵相邻的树之间的间隔都是11米。我们可以把马路看成一个数轴,马路的一端在数轴00的位置,另一端在L的位置;数轴上的每个整数点,即0,1,2,…,L0,1,2,…,L,都种有一棵树。
由于马路上有一些区域要用来建地铁。这些区域用它们在数轴上的起始点和终止点表示。已知任一区域的起始点和终止点的坐标都是整数,区域之间可能有重合的部分。现在要把这些区域中的树(包括区域端点处的两棵树)移走。你的任务是计算将这些树都移走后,马路上还有多少棵树。Input
第一行有22个整数(1≤L≤10000)和(1≤M≤100),L代表马路的长度,M代表区域的数目,L和M之间用一个空格隔开。
接下来的M行每行包含22个不同的整数,用一个空格隔开,表示一个区域的起始点和终止点的坐标。Sample Input
500 3
150 300
100 200
470 471Sample Output
298
AC CODE
/** Copyright (c) 2019 Ng Kimbing, HNU, All rights reserved. May not be used, modified, or copied without permission.* @Author: Ng Kimbing, HNU.* @LastModified:2019-04-18 T 14:10:41.546 +08:00*/
package ACMProblems.LuoGuTrainning;import static ACMProblems.ACMIO.*; //My IOpublic class Main {private static int maxNum;private static int infinite = 1 << 30;private static int[] sTree; //线段树private static void setInterval(int currIndex, int left, int right, int targetL, int targetR, int value) {if (left > targetR || right < targetL)return;if (left == right) {sTree[currIndex] = value;return;}int mid = (left + right) >> 1;setInterval(currIndex << 1, left, mid, targetL, targetR, value);setInterval(currIndex << 1 | 1, mid + 1, right, targetL, targetR, value); //recursively call setInterval(k*2+1,mid+1,right,y,x)sTree[currIndex] = sTree[currIndex << 1] + sTree[currIndex << 1 | 1];}private static int find(int fromY, int toY, int currPos, int left, int right) {if (toY < left || fromY > right)return infinite;if (left >= fromY && right <= toY)return sTree[currPos];int mid = (left + right) >> 1;return Math.min(find(fromY, toY, currPos << 1, left, mid), find(fromY, toY, currPos << 1 | 1, mid + 1, right));}private static void setInterval(int left, int right, int value) {setInterval(1, 0, maxNum, left, right, value);}public static void main(String[] args) throws Exception {setStream(System.in);maxNum = nextInt();sTree = new int[4 * maxNum + 10];setInterval(0, maxNum, 1);int caseNum = nextInt();while (caseNum-- != 0) {int a = nextInt();int b = nextInt();setInterval(a, b, 0);}out.println(sTree[1]);out.flush();}
}
更多推荐
(水题)洛谷P1047 校门外的树
发布评论