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

和为给定数

用双指针遍历,以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;
}
相关推荐
不会就选b3 小时前
算法日常・每日刷题--<贪心>14
算法
初願致夕霞3 小时前
C++11:类型推导与完美转发复盘笔记
c++
小猪写代码3 小时前
C++中什么是类,什么是对象
c++
mmmmath_35 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z6 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧7 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背7 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝7 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
HZZD_HZZD7 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法