Day1
知识点:
- 快速排序的应用
- nth_element()函数应用
- 三分法(转载:三分法详解)
- 模拟退火算法(了解)
题目分析:
该题代码:(C++)
写法1:
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
const int n = 100010;
int a[n];
int main(){
int m;
cin>>m;
for(int i=0;i<m;i++)
cin>>a[i];
sort(a,a+m);
//nth_element(a,a+(m/2);a+n);
int res = 0;
for(int i=0;i<m;i++)
res += abs(a[i]-a[m/2]);
cout<<res;
return 0;
}
写法2:
#include
#include<bits/stdc++.h>
using namespace std;
const int n = 100010;
int a[n];
int main(){
int m;
cin>>m;
for(int i=0;i<m;i++)
cin>>a[i];
nth_element(a,a+m/2,a+m);
int res = 0;
for(int i=0;i<m;i++)
res += abs(a[i]-a[m/2]);
cout<<res<<endl;
return 0;
}
注解:关于nth_element函数用法可参考:STL 之 nth_element详解(转载)
三分法:
代码:(原文链接:https://www.acwing.com/solution/content/29660/)
#include<cstdio>
#include<vector>
#include<cmath>
#include<iostream>
using namespace std;
const int N = 10010;
const double eps = 1e-4;
int n;
double x[N], y[N];
double dis1(double x1, double y1)
{
double sum = 0.0;
for(int i=0;i<n;i++){
sum += sqrt((x[i] - x1)*(x[i] - x1) + (y[i] - y1) * (y[i] - y1));
}
return sum;
}
double dis(double x1)
{
double l = 0.0, r = 10000.0;
int i = 0;
while(r - l >= eps){
double margin = (r - l)/3.0;
double m1 = l + margin;
double m2 = m1 + margin;
if(dis1(x1, m1) <= dis1(x1, m2)) r = m2;
else l = m1;
}
return dis1(x1, l);
}
int main()
{
scanf("%d", &n);
for(int i=0;i<n;i++){
scanf("%lf%lf", &x[i], &y[i]);
}
double l = 0.0, r = 10000.0;
while(r - l >= eps){
double margin = (r - l) / 3.0;
double m1 = l + margin;
double m2 = m1 + margin;
if(dis(m1) <= dis(m2)) r = m2;
else l = m1;
}
printf("%d", (int)(dis(l)+0.5));
}