和为给定数 与 最匹配的矩阵

和为给定数

用双指针遍历,以m与arri + arrj之间的大小关系进行对i、j的修改。

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
vector<long long> arr;
int main(){
    int n;
    cin >> n;
    for(int i = 0;i < n;i++){
        long long now;
        cin >> now;
        arr.push_back(now);
    }
    sort(arr.begin(),arr.end());
    long long m;
    cin >> m;
    int i = 0,j = n-1;
    while(i < j){
        if(m == arr[i] + arr[j]){cout << arr[i] << ' ' << arr[j] << endl;return 0;}
        if(m < arr[i] + arr[j]) j--;
        else i++;
    }
    // for(int i = 0;i < n;i++) cout << arr[i] << ' ';
    cout << "No" << endl;
    return 0;
}

最匹配的矩阵

遍历矩阵,进行对所有绝对值差的和的更新并记录此时的行号与列号,最后输出。

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 105;
int A[N][N],B[N][N];
int m,n,r,s;

int k(int a,int b){
    int total = 0;
    for(int i = a;i < a + r;i++){
        for(int j = b;j < b + s;j++){
            total += max(A[i][j],B[i - a + 1][j - b + 1]) - min(A[i][j],B[i - a + 1][j - b + 1]);
        }
    }
    return total;
}

int main(){
    cin >> m >> n;
    for(int i = 1;i <= m;i++){
        for(int j = 1;j <= n;j++){
            cin >> A[i][j];
        }
    }
    cin >> r >> s;
    for(int i = 1;i <= r;i++){
        for(int j = 1;j <= s;j++){
            cin >> B[i][j];
        }
    }
    int ans = r*s*N,ans_l = 0,ans_r = 0;
    for(int line = 1;line <= m - r + 1;line++){
        for(int row = 1;row <= n - s + 1;row++){
            int val = k(line,row);
            if(val < ans){//更新
                ans = val;
                ans_l = line;
                ans_r = row;
            }
        }
    }
    for(int i = ans_l;i < ans_l + r;i++){
        for(int j = ans_r;j < ans_r + s;j++){
            cout << A[i][j] << ' ';
        }
        cout << endl;
    }
    return 0;
}
相关推荐
郑州光合科技余经理26 分钟前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
To_OC3 小时前
LC 35 搜索插入位置:二分查找谁都会,边界条件谁写谁懵
javascript·算法·leetcode
码哥DFS3 小时前
二叉树的直径
开发语言·javascript·算法
营养充电站6 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
人工智能·算法·docker·jupyter
啊啊啊啊啊!!!!7 小时前
【c++】stack和queue的接口使用以及底层实现
开发语言·c++
技术小黑7 小时前
RNN算法实战系列05 | 天气预测
人工智能·rnn·算法
歪歪歪比巴卜9 小时前
服务商批量接手客户跨平台社媒账号的技术落地:体检体系与重启架构
矩阵·架构·aigc
比卡超哥9 小时前
Ctorch开发日志——矩阵乘法优化及数学原理
线性代数·矩阵
(Charon)9 小时前
【C++】锁与原子操作(四):自旋锁的完整实现与性能优化
c语言·开发语言·c++