CSP 2017年12月第1题 最小差值
-
一开始可以直接建一个数组 arr[1005] = {0}
-
然后使用
sort函数将所读入的数据从大到小排序,这样的话,最小差值一定在相邻两个数之间发生并且前后相减一定>=0
-
然后循环,取出其中最小的即可
#include<bits/stdc++.h>
using namespace std;
int arr[1005]={0};
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&arr[i]);
int ans=100000;
sort(arr+1,arr+n+1,cmp);//从大到小排序 保证值>=0
for(int i=1;i<n;i++)
{
int temp = arr[i]-arr[i+1];
if(ans>=temp)
ans = temp;
}
printf("%d",ans);
return 0;
}
本文详细解析了CSP2017年12月第一题的解决方案,通过创建数组并使用sort函数对输入数据进行降序排序,确保最小差值发生在相邻元素间。代码实现简洁高效,适用于解决类似数据排序与比较问题。
2037

被折叠的 条评论
为什么被折叠?



