hihocoder 1077 线段树 java实现

来源:互联网 发布:管家婆软件使用感想 编辑:程序博客网 时间:2024/06/08 00:38

package tree;


import java.util.Scanner;


/*

 * 10

3655 5246 8991 5933 7474 7603 6098 6654 2414 884

 */

public class Week19 {

privatestatic int dataIndex = 0;

privatestatic 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(inti=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, Stringdata){

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;

returnnode;

}

else{

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

returnnode;

}

}


public static void query(intfirstnum, intsecondnum, node19 root){

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

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

elseif(root.value <maximum) maximum =root.value;

}

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

elseif(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(intfirstnum, intsecondnum, 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{

intleft;

intright;

intvalue;

node19 leftChild;

node19 rightChild;

public node19(intleft, int right){

this.left =left;

this.right =right;

}


}



0 0
原创粉丝点击