题解 | #牛牛的数组匹配#
牛牛的数组匹配
https://www.nowcoder.com/practice/3d3406f4a7eb4346b025cc592be5b875
#include<stdio.h> #include<stdlib.h> int main() { int n = 0; int m = 0; int a[10] = { 0 }; int b[10] = { 0 }; scanf("%d %d", &n, &m);//输入数组a和数组b的元素个数 int a_sum = 0; for (int i = 0; i < n; i++)//给数组a各元素赋值,并求和。 { scanf("%d", &a[i]); a_sum = a_sum + a[i]; } for (int i = 0; i < m; i++)//给数组b各元素赋值 { scanf("%d", &b[i]); } int ret = 9999;//ret作为[b数组的子数组元素之和]与[数组a所有元素之和]的差,小于这个值就表示有新的子数组出现。 int record_i = 0;//记录左下标i int record_j = 0;//记录右下标j //子数组由最后面的连续数组开始组成 //例,b[4]={1,2,3,4} //4 //3 4 //2 3 4 //1 2 3 4 //3 //2 3 //1 2 3 //2 //1 2 //1 for (int j = m - 1; j >= 0; j--)//j的下标必须在数组范围内 { for (int i = j; i >= 0; i--)//i的下标必须在数组范围内 { int sum = 0; for (int x = i; x <= j; x++)//计算从b[i]到b[j]的所有元素之和sum { sum = sum + b[x]; } if (abs(sum - a_sum) <= ret) { ret = abs(sum - a_sum); record_i = i; record_j = j; } } } for (int i = record_i; i <= record_j; i++) { printf("%d ", b[i]); } return 0; }