关闭

hihocoder 1077 线段树 java实现

标签: hihocoderjava算法线段树1077
255人阅读 评论(0) 收藏 举报
分类:

package tree;


import java.util.Scanner;


/*

 * 10

3655 5246 8991 5933 7474 7603 6098 6654 2414 884

 */

public class Week19 {

private static int dataIndex = 0;

private static int maximum = 0;


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int nodenum = Integer.parseInt(scanner.nextLine());

String nodedata = scanner.nextLine();

node19 root = Week19.creSegTree(1, nodenum, nodedata);

int querynum = Integer.parseInt(scanner.nextLine());

for(int i=0; i<querynum; i++){

String querydata = scanner.nextLine();

int type = Integer.parseInt(querydata.split(" ")[0]);

int firstnum = Integer.parseInt(querydata.split(" ")[1]);

int secondnum = Integer.parseInt(querydata.split(" ")[2]);

if(type == 0){

query(firstnum, secondnum, root);

System.out.println(maximum);

maximum = 0;

}

if(type == 1) update(firstnum, secondnum, root);

}

}


public static node19 creSegTree(int left, int right, String data){

node19 node = new node19(left, right);

if(left != right){

node19 node1 = creSegTree(left, ((left + right) / 2), data);

node19 node2 = creSegTree(((left + right) / 2) + 1, right, data);

node.value = node1.value > node2.value ? node2.value : node1.value;

node.leftChild = node1;

node.rightChild = node2;

return node;

}

else{

node.value = Integer.parseInt(data.split(" ")[dataIndex++]);

return node;

}

}


public static void query(int firstnum, int secondnum, node19 root){

if(firstnum == root.left && secondnum == root.right){

if(maximum == 0) maximum = root.value;

else if(root.value < maximum) maximum = root.value;

}

else if(firstnum > (root.left + root.right) / 2) query(firstnum, secondnum, root.rightChild);

else if(secondnum < (root.left + root.right) / 2 + 1) query(firstnum, secondnum, root.leftChild);

else{

query(firstnum, (root.left + root.right) / 2, root.leftChild);

query((root.left + root.right) / 2 + 1, secondnum, root.rightChild);

}

}


public static void update(int firstnum, int secondnum, node19 root){

if(root.left == firstnum && root.right == firstnum) root.value = secondnum;

else if(firstnum < (root.left + root.right) / 2 + 1){ 

update(firstnum, secondnum, root.leftChild);

root.value = root.leftChild.value > root.rightChild.value ? root.rightChild.value : root.leftChild.value;

}

else if(firstnum > (root.left + root.right) / 2){ 

update(firstnum, secondnum, root.rightChild);

root.value = root.leftChild.value > root.rightChild.value ? root.rightChild.value : root.leftChild.value;

}

}

}


class node19{

int left;

int right;

int value;

node19 leftChild;

node19 rightChild;

public node19(int left, int right){

this.left = left;

this.right = right;

}


}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1300次
    • 积分:81
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档