zoukankan      html  css  js  c++  java
  • nyoj 119 士兵杀敌(三) 【线段树】【单点更新】

    题意:。

    。。

    策略如题。

    思路:我们先如果仅仅求某一区间的最大值。我们仅仅须要利用线段树的模板。仅仅须要初始化和询问的时候小小的改动一下。改成祖先结点储存的不再是子节点的和而是两个子节点之间的最大值,这样我们能够求出最大值了,最小值也是这样求。

    注意:由于询问的时候既要求最大值又要求最小值。所以要返回结构体。

    代码:

    #include <stdio.h>
    #include <string.h>
    #define M 100005
    
    struct node{
    	int left, right;
    	int max, min;
    };
    node s[M*4];
    
    void creat(int left, int right, int pos){
    	s[pos].left = left;
    	s[pos].right = right;
    	if(left == right){
    		scanf("%d", &s[pos].min);
    		s[pos].max = s[pos].min;
    		return;
    	}
    	int mid = (right+left)>>1;
    	creat(left, mid, pos<<1);
    	creat(mid+1, right, pos<<1|1);
    	s[pos].max = s[pos<<1].max>s[pos<<1|1].max?

    s[pos<<1].max:s[pos<<1|1].max; s[pos].min = s[pos<<1].min<s[pos<<1|1].min?

    s[pos<<1].min:s[pos<<1|1].min; } node query(int left, int right, int pos){ //要返回结构体 if(left == s[pos].left&&right == s[pos].right){ return s[pos]; } int mid = (s[pos].left+s[pos].right)>>1; if(right <= mid) return query(left, right, pos<<1); else if(left > mid) return query(left, right, pos<<1|1); else{ node temp1 = query(left, mid, pos<<1); node temp2 = query(mid+1, right, pos<<1|1); node temp; temp.max = temp1.max>temp2.max?temp1.max:temp2.max; temp.min = temp1.min<temp2.min?temp1.min:temp2.min; return temp; } } int main(){ int n, q, a, b; scanf("%d%d", &n, &q); creat(1, n, 1); while(q --){ scanf("%d%d", &a, &b); node temp = query(a, b, 1); printf("%d ", temp.max-temp.min); } return 0; }


    题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=119

  • 相关阅读:
    iOS 适配iPhoneX上tableHeaderView发生了高度拉伸、UI出现的空白间距
    无线加密WEP、WPA、WPA2及TKIP、AES
    字符替换操作
    jQuery版本升级问题汇总
    ipv6服务器及环境搭建
    git删除某次提交操作
    五种IO模型
    jQuery1.6以上attr改用prop
    线程创建pthread_create用法(转)
    网络字节序与主机字节序
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6932648.html
Copyright © 2011-2022 走看看