The Water Problem(取最大值)

本文介绍了一个使用C++实现的简单程序,该程序能够读取一组整数,并通过多次查询来找出指定区间内的最大值。这个算法适用于解决一些基本的数据结构和算法问题。

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

The Water Problem(取最大值)


这里写图片描述


#include <iostream>

using namespace std;

int t,n,q,l,r,i;
int a[1010];

int MAX(int r,int l)
{
    return r>l?r:l;
}

int main()
{
    cin>>t;
    while(t--)
    {
        cin>>n;
        for(i=1; i<=n; i++)
        {
            cin>>a[i];
        }
        cin>>q;
        for(i=0; i<q ;i++)
        {
            int num=0;
            cin>>l>>r;
            for(int j=l; j<=r; j++)
            {
                num=MAX(num,a[j]);
            }
            cout<<num<<endl;
        }
    }
    return 0;
}
% MATLAB file geost_adjust_2.m % Geostrophic adjustment in 1-d shallow water model for initial height % 30disturbance consisting of a confined surface displacement % defined by the function h(x) = -hm/(1+(x/L)^2). % Student can vary Coriolis parameter and width of initial height disturbance % to see influence of rotation and scale on the response % Fast fourier transform is used to determine spectral coefficients for % solution using ode solver then inverse transforming. disp('barotropic Rossby adjustment problem') disp('initial condition h(x) = -hm/(1+(x/L)^2 ') clear all close all lat = input('give latitude in degrees '); cor = 2*7.2921e-5*sin(pi*lat/180); runtime = input('integration time in days '); time = runtime*24*3600; L = input('give zonal scale of initial disturbance in km (200 km minimum) '); Lx = 16000; % Lx is the width of the domain in km k = 2*pi/(Lx*1.e3); % lowest zonal wavenumber in m-1 csq = 20^2; % shallow water speed squared csq = gH alph = 1.e-5; % damping rate for u component N = 128; % number of modes for Fourier transform x = linspace(0, Lx, N); xm = Lx/2; % location of maximum disturbance in km % set the initial conditions on u(x), v(x), p(x) p0 = -400./(1+((x-xm)/L).^2); % Fourier transform p0(x) to get P0(s) disp('please wait while time integration is performed') P0 = fft(p0,N); U0 = zeros(size(P0)); V0 =zeros(size(P0)); options = []; % place holder for s = 1: N/2; ls = +i*k*(s-1); als = alph*(s/N)^2; % solution is saved once every two hours [t,y] = ode45('yprim_adj_2',[0:7200:time],[U0(s) V0(s) P0(s)],... options,cor,csq,ls,alph); U(:,s) = y(:,1); V(:,s) = y(:,2); P(:,s) = y(:,3); end dt = length(t); for j = 1:dt; u(j,:) = real(ifft(U(j,:),N)); v(j,:) = real(ifft(V(j,:),N)); p(j,:) = real(ifft(P(j,:),N)); end figure(1) axis square set(gca,'NextPlot','replacechildren') for j = 1:dt subplot(3,1,1), plot(x,u(j,:)) axis([0 Lx -6 6]) xlabel('x (km)'), ylabel('u velocity (m/s)') str1 = ['time = ' num2str(t(j)/3600) ' hours']; title(str1, 'Fontsize',12) subplot(3,1,2), plot(x,v(j,:)) axis([0 Lx -3 3]) xlabel('x (km)'), ylabel( 'v velocity (m/s)') subplot(3,1,3), plot(x,p(j,:)) axis([0 Lx -400 100]) xlabel('x (km)'), ylabel('height (m)') H= gcf; M(:,j) = getframe(H); end movie(H,M,1,8) disp('to repeat movie enter command movie(H,M,2) ') 我通过上述程序得到了纬度30,时间为5,扰动距离为500的动画图像,现在我想求在v图像中最大值与最小值的横坐标是什么,并算出差值,要求返回一个平均数,只要一个数就行
06-05
for t in range(len(q_in_base) - N): # 定义优化变量 x_mpc = cp.Variable(N + 1) u = cp.Variable(N) # 获未来N步的入库流量 q_future = q_in_base[t:t + N] # 约束条件 constraints = [x_mpc[0] == current_x_mpc] # 初始状态为MPC预测值 for k in range(N): delta_y = (q_future[k] - u[k]) / Ar # MPC内部使用简化模型 constraints.append(x_mpc[k + 1] == x_mpc[k] + delta_y) constraints.append(u[k] >= 0) constraints.append(u[k] <= max_flow_rate) if k > 0: constraints.append(cp.abs(u[k] - u[k - 1]) <= max_delta_flow_rate) # 添加位上下限约束 constraints.append(x_mpc >= min_water_level) constraints.append(x_mpc <= max_water_level) # 目标函数 max_state_deviation = max(target_level - min_water_level, max_water_level - target_level) normalized_state_error = (x_mpc[1:] - target_level) / max_state_deviation normalized_u = u / max_flow_rate normalized_delta_u = (u[1:] - u[:-1]) / max_delta_flow_rate cost = Q_weight * cp.sum_squares(normalized_state_error) + \ R_flow_weight * cp.sum_squares(normalized_u) + \ R_smooth_weight * cp.sum_squares(normalized_delta_u) problem = cp.Problem(cp.Minimize(cost), constraints) # 求解优化问 try: problem.solve(solver=cp.SCS, eps=1e-5, verbose=False) if problem.status not in [cp.OPTIMAL, cp.OPTIMAL_INACCURATE]: raise RuntimeError(f"问未最优求解: {problem.status}") optimal_u = u.value[0] if u.value is not None else 0 print(f"时间步 {t + 1} | 状态: {problem.status} | 成本: {cost.value:.2f} | 最优控制量: {optimal_u:.2f}") except Exception as e: print(f"时间步 {t + 1} | 求解失败: {e},使用默认控制量 0") optimal_u = 0 optimal_u_all.append(optimal_u) # 保存MPC预测的第一个步长后的位(开环预测) if x_mpc.value is not None: mpc_predicted_next_level = x_mpc.value[1] future_y_mpc.append(mpc_predicted_next_level) else: future_y_mpc.append(current_x_mpc) # 如果求解失败,使用当前状态 # 获当前入库流量 q_in_current = q_in_base[t] # 运行IDZ模型,获实际位 _, y_IDZ = idz_simulator_step( current_y=current_y_real, u_current=optimal_u, q_in_current=q_in_current, q_in_prev=q_in_prev, bd1=bd1, bd2=bd2, Ar=Ar, dt=dt ) # 更新MPC初始状态为IDZ模型输出 current_x_mpc = y_IDZ # 更新实际位 current_y_real = y_IDZ future_y_real.append(current_y_real) # 更新上一时刻入库流量 q_in_prev = q_in_current print(f"时间步 {t + 1} | 反馈校正后位: {current_y_real:.2f}")
08-15
### C++ 实现最大桶问(Max Water Bucket Problem) 最大桶问通常指的是给定一组高度值,找到两个垂直线之间的区域最大化的问。这是一个经典的双指针算法问。 以下是基于站内引用的内容所描述的解决方案[^1]: ```cpp #include <vector> #include <algorithm> // std::max 和 std::min using namespace std; class Solution { public: int maxArea(vector<int>& height) { int ans = 0; int l = 0, r = static_cast<int>(height.size()) - 1; // 初始化左指针和右指针 while (r > l) { // 当右指针大于左指针时继续循环 ans = max(ans, (r - l) * min(height[l], height[r])); // 计算当前面积并更新最大值 if (height[l] <= height[r]) { // 如果左边的高度小于等于右边,则移动左指针 ++l; } else { // 否则移动右指针 --r; } } return ans; // 返回最终的最大面积 } }; ``` 上述代码实现了 `maxArea` 函数来计算容器可以容纳的最大量。它利用了双指针技术,初始设置左右指针分别位于数组两端,并逐步向中间靠拢,每次比较当前宽度乘以较矮的一侧高度的结果,从而得到可能的最大面积。 #### 关键点解释 - **初始化指针**:左指针 `l` 设置为起点索引 `0`,右指针 `r` 设置为终点索引 `size()-1`。 - **核心逻辑**:通过 `(r-l)*min(height[l], height[r])` 来计算当前状态下可盛放的量,并不断尝试更新全局变量 `ans` 的值。 - **指针移动策略**:如果左侧柱子低于右侧柱子,则增加左侧指针;反之减少右侧指针。这样能够保证下一次迭代有机会获得更大的潜在容量。 此方法的时间复杂度为 O(n),其中 n 是输入数组长度,因为每轮迭代都会使某个方向上的边界缩小一步直到两者相遇为止。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值