Ray, Pass me the dishes! UVALive - 3938 线段树

本文介绍了解决RMQ问题的一种方法,使用线段树维护区间内的最大子段和及其位置。通过分治思想,文章详细解释了如何在每个节点维护最大前缀、最大后缀和最大子段的值,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这题淘米居然要用long long!!!

这题淘米居然要用long long!!!

这题淘米居然要用long long!!!

这题淘米居然要用long long!!!

这题淘米居然要用long long!!!

这题淘米居然要用long long!!!

这题淘米居然要用long long!!!

这题淘米居然要用long long!!!

这题淘米居然要用long long!!!

心态有点崩。。。。

题目还是比较简单(我呸)

题目大意

大意是给定长度为n的区间进行m次询问,每次询问形式为[a,b],给出这个区间内【相加之和最大】的子段的起点和终点,若多解,则输出x小,若仍多解,则输出y小。

思路分析

基本思路分治法,《算法竞赛入门经典-训练指南》P201有思路(如果我讲不清楚麻烦自行翻书)

RMQ问题很多都要用线段树来解决,然而这题乍一看不能用线段树来维护,因为父节点的值不能通过简单合并两个子结点的值来获得

但是实际上,我们可以对每个节点维护3个值:

最大前缀,最大后缀,最大子段

什么意思呢?线段树的每个节点都会对应到一个区间上,假设这个区间为[l,r],那么最大前缀即为使al+al+1+...+ax最大的x,最大后缀即为使ax+ax+1+...+ar最大的x,最大子段即为使ax+ax+1+...+ay最大的x和y

考虑如何维护这三个值

维护前缀

当维护父节点的前缀时,由于起点已知,故我们讨论终点。终点只可能在左子结点中,或者在右子结点中

若终点在左子结点中,那么父节点的前缀等于左子结点的前缀,因为左子结点的前缀是终点在左子结点中最大的那个。

若终点在右子结点中,则父节点的前缀等于左子结点的区间和,再加上右子结点的最大前缀,其终点为右子结点最大前缀的终点。因为终点在右子结点时,可以看成是所有右子结点的前缀同时加上左子结点的区间和,原来右子结点的最大前缀仍然是最大的。

(我可能没讲清楚但是我觉得自己想也很容易明白吧)

维护后缀

这个思路和维护前缀相似,由于终点已知,所以我们讨论起点。这里要注意题目要求的是使x尽量小,所以我们应当先讨论起点在左子结点中,再讨论起点在右子结点中

当起点在左子结点中时,父节点的后缀等于左子结点的最大后缀,再加上右子结点的区间和,其起点为左子结点的最大后缀的起点

当起点在右子结点中是,父节点的后缀等于右子结点的后缀

维护子段

由于子段的起点和终点都不确定,所以这里我们采取分治的思想讨论。有3种情况:子段完全在左子结点中,子段完全在右子结点中,子段部分在左子结点中,部分在右子结点中。

当子段完全在左子结点(或右子结点)中时,最大的子段等于左子结点(或右子结点)的最大子段。

当子段跨越两个子结点时,最大子段恰好为左子结点的最大后缀,再加上右子结点的最大前缀。

这题要用long long

大概是我做的太少对数字还不够敏感,虽然int能装1e9,但是int最多也就能装2*1e9多一点,但是这里要求的是区间和,也就是说最坏情况下,区间长度为3就足够炸int了,所以显然是不能用int的。。

看博客开篇我深深的怨念。。。。你猜我debug多少次才发现这个东西。。。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x3f3f3f3f
#define maxn 524290
using namespace std;
typedef long long ll;
typedef long long LL;
typedef struct {
    bool useful;//标记结点是否有效 
    ll sum;
    ll maxSub, maxPre, maxSuf;//最大子段,最大前缀,最大后缀
    int maxSubBegin, maxSubEnd, maxPreEnd, maxSufBegin;//最大子段起止点,最大前缀终点,最大后缀起点
} Node;
int n;//线段树结点个数
Node dat[2*maxn];//线段树结点
//void PrintNode(Node node) {//调试用 
//  cout<<endl;
//  cout<<"useful="<<node.useful<<",sum="<<node.sum<<endl;
//  cout<<"maxSub="<<node.maxSub<<",maxSubBegin="<<node.maxSubBegin<<",maxSubEnd="<<node.maxSubEnd<<endl;
//  cout<<"maxPre="<<node.maxPre<<",maxPreEnd="<<node.maxPreEnd<<endl;
//  cout<<"maxSuf="<<node.maxSuf<<",maxSufBegin="<<node.maxSufBegin<<endl;
//  cout<<endl;
//}
void init(int n_) {
    n = 1;
    while(n < n_) n <<= 1;
    for(int i = 0; i < 2*n-1; i++) dat[i].useful = false;//初始化为无效结点 
}
Node unite(Node x, Node y) {//将x和y视为相邻的两个结点(x左y右)合并,返回新节点 
    if(!x.useful) return y;
    if(!y.useful) return x;
    Node node; node.useful = true;
//更新区间和
    node.sum = x.sum + y.sum;
//更新最大子段,为了保证x小y小,从小的开始更新 
    //取子段较大的儿子的最大子段
    //开始取左儿子 
    node.maxSub = x.maxSub;
    node.maxSubBegin = x.maxSubBegin;
    node.maxSubEnd = x.maxSubEnd;

    //若中间交叉子段更大,则更新为中间交叉子段相应的值 
    if(x.maxSuf + y.maxPre > node.maxSub) {
        node.maxSub = x.maxSuf + y.maxPre;
        node.maxSubBegin = x.maxSufBegin;
        node.maxSubEnd = y.maxPreEnd;
    }

    if(y.maxSub > node.maxSub) {//右儿子较大 
        node.maxSub = y.maxSub;
        node.maxSubBegin = y.maxSubBegin;
        node.maxSubEnd = y.maxSubEnd;
    }
//更新最大前缀
    //先取左结点的最大前缀(使y小),如果最大前缀不跨越两个区间,那么这个就是最终前缀 
    node.maxPre = x.maxPre;
    node.maxPreEnd = x.maxPreEnd;

    //如果最大前缀跨越两个区间,更新node 
    if(x.sum + y.maxPre > node.maxPre) {
        node.maxPre = x.sum + y.maxPre;
        node.maxPreEnd = y.maxPreEnd;
    }
//更新最大后缀
    //先取跨越两个区间的最大后缀(使x小) 
    node.maxSuf = x.maxSuf + y.sum;
    node.maxSufBegin = x.maxSufBegin;

    //如果最大后缀在右结点,更新node 
    if(y.maxSuf > node.maxSuf) {
        node.maxSuf = y.maxSuf;
        node.maxSufBegin = y.maxSufBegin;
    }
    return node;
} 
void update(int k, Node aa) {
    k += n-1;
    dat[k] = aa;
    while(k > 0) {
        k = (k-1)>>1;
        dat[k] = unite(dat[2*k+1], dat[2*k+2]);
    }
}
Node query(int a, int b, int k, int l, int r) {
    if(r <= a || b <= l) {
        Node node; node.useful = false;
        return node;//区间不相交 
    }
    if(a <= l && r <= b) return dat[k];//区间完全包含 
    Node vl = query(a, b, 2*k+1, l, (l+r)>>1);//区间相交 
    Node vr = query(a, b, 2*k+2, (l+r)>>1, r);
//  cout<<"query("<<a<<","<<b<<","<<k<<","<<l<<","<<r<<")"<<endl;
//  PrintNode(vl); PrintNode(vr);
    return unite(vl, vr);
}
int main() {
    int N, m, Case = 0;
    while(cin>>N>>m) {
        init(N);//线段树初始化 
        for(int i = 0; i < N; i++) {
            Node node; node.useful = true;
            LL a; cin>>a;
            node.sum = node.maxPre = node.maxSub = node.maxSuf = a;//构建第i个结点 
            node.maxPreEnd = node.maxSubBegin = node.maxSubEnd = node.maxSufBegin = i+1;
            update(i, node);//将第i个结点加入线段树 
        }

//      for(int i = 0; i < 2*n-1; i++) PrintNode(dat[i]);

        cout<<"Case "<<++Case<<":"<<endl;
        while(m--) {//处理m次询问 
            int l, r; cin>>l>>r;
            Node node = query(l-1, r, 0, 0, n);//取得区间对应的结点信息 
//          PrintNode(node);
            int x, y;
            x = l; y = node.maxPreEnd;
            if(node.maxSub > node.maxPre) {
                x = node.maxSubBegin;
                y = node.maxSubEnd;
            }
            if(node.maxSuf > node.maxPre && node.maxSuf > node.maxSub) {
                x = node.maxSufBegin;
                y = r;
            }
            cout<<x<<" "<<y<<endl;
        }
    }
    return 0;
}
在原有的页面上添加 ,底部 已加载完毕 分割线 避免被购物车挡住 原有页面如下 : <template> <view class="shop-container"> <!-- 顶部固定区域 --> <view class="fixed-header"> <!-- 搜索栏 --> <view class="search-bar"> <uni-search-bar placeholder="搜索菜品" radius="100" @confirm="searchDish" @input="searchInput" cancelButton="none" /> </view> <!-- 菜品分类 --> <scroll-view class="category-scroll" scroll-x="true"> <view v-for="(category, index) in categories" :key="index" class="category-item" :class="{ active: currentCategory === index }" @click="changeCategory(index)" > {{ category.name }} </view> </scroll-view> </view> <!-- 菜品列表 --> <scroll-view class="dish-list" scroll-y="true"> <view v-for="(dish, index) in filteredDishes" :key="dish.id" class="dish-item"> <!-- 菜品图片 --> <image class="dish-image" :src="dish.image" mode="aspectFill" /> <!-- 菜品信息 --> <view class="dish-info"> <text class="dish-name">{{ dish.name }}</text> <text class="dish-price">¥{{ dish.price.toFixed(2) }}</text> <text class="dish-stock" :class="{ 'low-stock': dish.stock < 5 }"> 剩余: {{ dish.stock }}份 </text> </view> <!-- 数量选择器 --> <view class="quantity-selector" v-if="cartItemQuantity(dish.id) > 0"> <button class="quantity-btn" @click="decreaseQuantity(dish)"> <uni-icons type="minus" size="16" color="#ff6b6b"></uni-icons> </button> <text class="quantity-text">{{ cartItemQuantity(dish.id) }}</text> <button class="quantity-btn" :disabled="cartItemQuantity(dish.id) >= dish.stock" @click="increaseQuantity(dish)" > <uni-icons type="plus" size="16" color="#ff6b6b"></uni-icons> </button> </view> <!-- 添加按钮 --> <view class="add-btn-container" v-else> <button v-if="dish.stock > 0" class="add-btn" :disabled="dish.stock <= 0" @click="addToCart(dish)"> <uni-icons type="plusempty" size="20" color="#fff"></uni-icons> </button> <text v-if="dish.stock <= 0" class="sold-out-text">已售罄</text> </view> </view> </scroll-view> <!-- 购物车底部栏 --> <view class="cart-bar" @click="showCartDetail"> <view class="cart-icon-container"> <uni-icons type="cart-filled" size="30" color="#fff"></uni-icons> <view v-if="cartItemCount > 0" class="cart-badge">{{ cartItemCount }}</view> </view> <text class="total-price">¥{{ totalPrice.toFixed(2) }}</text> <button class="checkout-btn" :disabled="cartItemCount === 0">去结算</button> </view> <!-- 购物车详情弹窗 --> <uni-popup ref="cartPopup" type="bottom" :maskClick="false"> <view class="cart-detail"> <view class="cart-header"> <text class="cart-title">已选菜品</text> <uni-icons type="close" size="24" color="#999" @click="closeCartDetail"></uni-icons> </view> <scroll-view class="cart-list" scroll-y="true"> <view v-for="(item, index) in cart" :key="item.id" class="cart-item"> <image class="cart-item-image" :src="item.image" mode="aspectFill" /> <view class="cart-item-info"> <text class="cart-item-name">{{ item.name }}</text> <text class="cart-item-price">¥{{ item.price.toFixed(2) }}</text> </view> <view class="cart-item-quantity"> <button class="cart-quantity-btn" @click="decreaseCartQuantity(item)"> <uni-icons type="minus" size="16" color="#ff6b6b"></uni-icons> </button> <text class="cart-quantity-text">{{ item.quantity }}</text> <button class="cart-quantity-btn" :disabled="item.quantity >= item.stock" @click="increaseCartQuantity(item)" > <uni-icons type="plus" size="16" color="#ff6b6b"></uni-icons> </button> </view> </view> </scroll-view> <view class="cart-footer"> <text class="cart-total">总计: ¥{{ totalPrice.toFixed(2) }}</text> <button class="cart-checkout-btn" @click="checkout">去结算</button> </view> </view> </uni-popup> </view> </template> <script> export default { data() { return { currentCategory: 0, // 当前选中的分类索引 searchKeyword: '', // 搜索关键词 cart: [], // 购物车 // 菜品分类 categories: [ { id: 0, name: '全部' }, { id: 1, name: '热销' }, { id: 2, name: '主食' }, { id: 3, name: '汤类' }, { id: 4, name: '小吃' }, { id: 5, name: '饮品' } ], // 菜品数据 dishes: [ { id: 1, name: '鱼香肉丝', price: 38, stock: 15, image: '/static/images/dishes/1.jpeg', category: 1 }, { id: 2, name: '宫保鸡丁', price: 42, stock: 8, image: '/static/images/dishes/2.jpeg', category: 1 }, { id: 3, name: '麻婆豆腐', price: 28, stock: 0, image: '/static/images/dishes/3.jpg', category: 1 }, { id: 4, name: '扬州炒饭', price: 25, stock: 12, image: '/static/images/dishes/4.jpeg', category: 2 }, { id: 5, name: '番茄鸡蛋面', price: 22, stock: 20, image: '/static/images/dishes/4.jpeg', category: 2 }, { id: 6, name: '酸辣汤', price: 18, stock: 5, image: '/static/images/dishes/4.jpeg', category: 3 }, { id: 7, name: '春卷', price: 15, stock: 3, image: '/static/images/dishes/4.jpeg', category: 4 }, { id: 8, name: '冰镇酸梅汤', price: 12, stock: 25, image: '/static/images/dishes/dish08.jpg', category: 5 } ] } }, computed: { // 过滤后的菜品列表 filteredDishes() { let result = [...this.dishes]; // 按分类过滤 if (this.currentCategory > 0) { result = result.filter(dish => dish.category === this.currentCategory); } // 按关键词搜索 if (this.searchKeyword) { const keyword = this.searchKeyword.toLowerCase(); result = result.filter(dish => dish.name.toLowerCase().includes(keyword) ); } return result; }, // 购物车商品数量 cartItemCount() { return this.cart.reduce((total, item) => total + item.quantity, 0); }, // 总金额 totalPrice() { return this.cart.reduce((total, item) => total + (item.price * item.quantity), 0); } }, methods: { // 切换分类 changeCategory(index) { this.currentCategory = index; }, // 搜索输入 searchInput(e) { this.searchKeyword = e.value; }, // 搜索确认 searchDish(e) { this.searchKeyword = e.value; }, // 获取菜品在购物车中的数量 cartItemQuantity(dishId) { const item = this.cart.find(item => item.id === dishId); return item ? item.quantity : 0; }, // 添加到购物车 addToCart(dish) { if (dish.stock <= 0) return; // 检查是否已在购物车 const existingItem = this.cart.find(item => item.id === dish.id); if (existingItem) { // 如果已在购物车,增加数量 this.increaseQuantity(dish); } else { // 添加到购物车 this.cart.push({ ...dish, quantity: 1 }); } }, // 增加菜品数量 increaseQuantity(dish) { const item = this.cart.find(item => item.id === dish.id); if (item && item.quantity < dish.stock) { item.quantity++; } }, // 减少菜品数量 decreaseQuantity(dish) { const item = this.cart.find(item => item.id === dish.id); if (item) { if (item.quantity > 1) { item.quantity--; } else { // 数量为1时减少则移除 this.cart = this.cart.filter(cartItem => cartItem.id !== dish.id); } } }, // 增加购物车中菜品数量 increaseCartQuantity(item) { const dish = this.dishes.find(d => d.id === item.id); if (dish && item.quantity < dish.stock) { item.quantity++; } }, // 减少购物车中菜品数量 decreaseCartQuantity(item) { if (item.quantity > 1) { item.quantity--; } else { // 数量为1时减少则移除 this.cart = this.cart.filter(cartItem => cartItem.id !== item.id); } }, // 显示购物车详情 showCartDetail() { if (this.cartItemCount > 0) { this.$refs.cartPopup.open(); } }, // 关闭购物车详情 closeCartDetail() { this.$refs.cartPopup.close(); }, // 结算 checkout() { uni.showToast({ title: '结算成功', icon: 'success' }); // 实际开发中这里会有支付流程 this.closeCartDetail(); } } } </script> <style lang="scss" scoped> .shop-container { display: flex; flex-direction: column; height: 100vh; background-color: #f5f5f5; padding-bottom: 100rpx; } /* 新增顶部固定容器 */ .fixed-header { position: sticky; top: 0; z-index: 1000; /* 确保在顶部 */ background: white; /* 背景色,避免滚动时内容透出 */ box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1); /* 添加阴影增强层次感 */ } .search-bar { padding: 20rpx; background-color: #fff; } .category-scroll { white-space: nowrap; background-color: #fff; padding: 20rpx 0; border-bottom: 1rpx solid #eee; } .category-item { display: inline-block; padding: 10rpx 30rpx; margin: 0 10rpx; border-radius: 30rpx; background-color: #f5f5f5; font-size: 28rpx; &.active { background-color: #ff6b6b; color: #fff; } } .dish-list { flex: 1; padding: 20rpx; /* 添加顶部内边距,避免内容被固定栏遮挡 */ // padding-top: 0; } .dish-item { display: flex; align-items: center; background-color: #fff; border-radius: 16rpx; margin-bottom: 15rpx; padding: 20rpx; box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05); } .dish-image { width: 180rpx; height: 180rpx; border-radius: 8rpx; margin-right: 20rpx; } .dish-info { flex: 1; display: flex; flex-direction: column; justify-content: space-between; } .dish-name { font-size: 28rpx; font-weight: bold; color: #333; } .dish-price { font-size: 30rpx; color: #ff6b6b; margin-top: 10rpx; } .dish-stock { font-size: 24rpx; color: #999; margin-top: 10rpx; &.low-stock { color: #ff6b6b; } } .add-btn-container { display: flex; align-items: center; } .add-btn { width: 70rpx; height: 70rpx; border-radius: 50%; background-color: #ff6b6b; display: flex; justify-content: center; align-items: center; color: #fff; font-size: 24rpx; padding: 0; margin: 0; &.disabled { background-color: #ccc; } } .sold-out-text { font-size: 28rpx; color: #999; padding: 10rpx 20rpx; background-color: #f5f5f5; border-radius: 8rpx; } .quantity-selector { display: flex; align-items: center; background-color: #fff; border-radius: 40rpx; padding: 6rpx; box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1); } .quantity-btn { width: 50rpx; height: 50rpx; border-radius: 50%; display: flex; justify-content: center; align-items: center; padding: 0; margin: 0; background-color: #fff; border: 1rpx solid #eee; } .quantity-text { font-size: 28rpx; min-width: 60rpx; text-align: center; font-weight: bold; } .cart-bar { position: fixed; bottom: 0; left: 0; right: 0; height: 100rpx; background-color: #333; display: flex; align-items: center; padding: 0 30rpx; color: #fff; z-index: 999; } .cart-icon-container { position: relative; margin-right: 20rpx; } .cart-badge { position: absolute; top: -10rpx; right: -10rpx; background-color: #ff6b6b; color: #fff; border-radius: 50%; width: 40rpx; height: 40rpx; display: flex; justify-content: center; align-items: center; font-size: 24rpx; } .total-price { flex: 1; font-size: 36rpx; font-weight: bold; } .checkout-btn { background-color: #ff6b6b; color: #fff; border-radius: 50rpx; padding: 0 40rpx; height: 70rpx; line-height: 70rpx; font-size: 30rpx; &[disabled] { background-color: #999; opacity: 0.6; } } /* 购物车详情弹窗样式 */ .cart-detail { background-color: #fff; border-top-left-radius: 20rpx; border-top-right-radius: 20rpx; padding: 30rpx; max-height: 80vh; display: flex; flex-direction: column; } .cart-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 20rpx; border-bottom: 1rpx solid #eee; margin-bottom: 20rpx; } .cart-title { font-size: 36rpx; font-weight: bold; color: #333; } .cart-list { flex: 1; max-height: 60vh; } .cart-item { display: flex; align-items: center; padding: 20rpx 0; border-bottom: 1rpx solid #f5f5f5; } .cart-item-image { width: 120rpx; height: 120rpx; border-radius: 8rpx; margin-right: 20rpx; } .cart-item-info { flex: 1; } .cart-item-name { font-size: 30rpx; color: #333; margin-bottom: 10rpx; } .cart-item-price { font-size: 28rpx; color: #ff6b6b; } .cart-item-quantity { display: flex; align-items: center; } .cart-quantity-btn { width: 50rpx; height: 50rpx; border-radius: 50%; display: flex; justify-content: center; align-items: center; padding: 0; margin: 0 10rpx; background-color: #fff; border: 1rpx solid #eee; } .cart-quantity-text { font-size: 28rpx; min-width: 60rpx; text-align: center; font-weight: bold; } .cart-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 20rpx; padding-top: 20rpx; border-top: 1rpx solid #eee; } .cart-total { font-size: 36rpx; font-weight: bold; color: #ff6b6b; } .cart-checkout-btn { background-color: #ff6b6b; color: #fff; border-radius: 50rpx; padding: 0 40rpx; height: 80rpx; line-height: 80rpx; font-size: 32rpx; } </style>
最新发布
07-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值