hihocoder 1077 线段树 java实现

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;

}


}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值