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

和为给定数

用双指针遍历,以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;
}
相关推荐
eggwyw7 小时前
C++ union 的一种妙用法
开发语言·c++
罗西的思考7 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
ShineWinsu9 小时前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步10 小时前
string的实现(1)
c++·笔记·visual studio
kyle~12 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
敲上瘾12 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
牢姐与蒯13 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好14 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
lcj251114 小时前
[C++] C++11
开发语言·c++·笔记
tellmewhoisi15 小时前
深度学习0:数学知识:(雅可比矩阵)
人工智能·深度学习·矩阵