数组的距离

 数组的距离

时间限制: 1 Sec  内存限制: 128 MB
提交: 1414  解决: 808
[提交] [状态] [讨论版] [命题人:外部导入]

题目描述

已知元素从小到大排列的两个数组x[]和y[],请写出一个程序算出两个数组彼此之间差的绝对值中最小的一个,这叫做数组的距离

输入

第一行为两个整数m, n(1≤m, n≤1000),分别代表数组f[], g[]的长度。 
第二行有m个元素,为数组f[]。 
第三行有n个元素,为数组g[]。

输出

数组的最短距离

样例输入:

5 5
1 2 3 4 5
6 7 8 9 10

样例输出:

1
扫描二维码关注公众号,回复: 4828668 查看本文章
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
/*
对Num数组中所有的元素使用sort函数由小到大排序 
*/
bool cmp(int a, int b)
{
	return a < b;
}
/*Num数组元素个数最多为1000000
定义在main之外,定义在main函数里面会报错*/
int Num[1000003]; 

int main()
{
	int m;
	int n;
	cin >> m >> n;
	/*定义两个数组并输入数据*/
	int num1[m];
	int num2[n];
	for(int i=0; i<m; i++)
	{
		cin >> num1[i];
	}
	for(int i=0; i<n; i++)
	{
		cin >> num2[i];
	}
	int count = 0;//用来记录Num数组中元素的个数,初始为0 
	for(int i=0; i<m; i++)
		for(int j=0; j<n; j++)
		{
			/*
			用数组Num记录num1和num2中两两元素差的绝对值 
			*/
			Num[count] = abs(num1[i] - num2[j]);
			count++;//数组中元素个数加1 
		}
	sort(Num,Num+count,cmp);//对Num数组中元素进行排序 
	cout << Num[0] << endl;//输出Num中最小的一个 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/tian_he_he/article/details/85228535