BJTU-OJ:小N的作业题(矩形面积内的元素权重求和,动态规划)

本文介绍了一种使用Java实现的方法,通过Scanner输入二维数组dep表示图的边及其消耗量,计算从任意两点之间的最短消耗路径。通过创建sums数组存储路径消耗和,最后解决给定两点间的最短消耗路径问题。
摘要由CSDN通过智能技术生成

在这里插入图片描述

import java.util.*;

public class Main {

   public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int dep[][] = new int [2001][2001];
        int n = sc.nextInt();
        for ( int i =0;i<n;i++){
            int a = sc.nextInt();
            int b = sc.nextInt();
            if (dep[a][b] == 0){
                dep[a][b] =  sc.nextInt();
            }else {
                dep[a][b] = dep[a][b] + sc.nextInt();
            }

        }
        int [][]sums = new int [2002][2002];//sums数组存储的内容是由(0,0)到(x,y)的所有消耗量的和,在这个数组中sums[0][0]、sums[i][0]、sums[0][j]都是没有被利用的部分
        for (int i =0;i < 2001;i++){
            int rowsum = 0;
            for (int j= 0; j < 2001;j++){
                rowsum += dep[i][j];
                sums[i+1][j+1] = sums[i][j+1] +rowsum;
            }
        }

        int m = sc.nextInt();
        for (int j =0;j < m;j++){
            int res= 0;
            int a1= sc.nextInt();
            int b1= sc.nextInt();
            int a2= sc.nextInt();
            int b2= sc.nextInt();

            int  reswWithoutLeftAndBottom =  sums[a2+1][b2+1]-sums[a2+1][b1+1]-sums[a1+1][b2+1]+sums[a1+1][b1+1];
            int left = 0;
            for (int i = b1;i <= b2 ;i++){
                left+= dep[a1][i];
            }
            int bottom = 0;
            for (int i = a1;i <= a2 ;i++){
                bottom+= dep[i][b1];
            }
            res = reswWithoutLeftAndBottom+left+bottom-dep[a1][b1];
            System.out.println(res);

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值