https://www.luogu.com.cn/problem/P1883
https://www.luogu.com.cn/problem/P3382
两道题都是三分
三分的思路是先确定左边界,和右边界
将这个区间三等分,比较函数值,得出有一部分区间一定不会出现极值
逐渐缩小区间,找到极值。
1883代码如下:
#include<stdio.h>
#include<math.h>
int a[10010], b[10010], c[10010];
double l=0,r=1000,mid1,mid2;
double max1=-INFINITY,max2=-INFINITY,ans1,ans2;
int main()
{
int n,m;
scanf("%d",&n);
for (int i=0;i<n;i++)
{
l=0;
r=1000;
max1=-INFINITY;
max2=-INFINITY;
scanf("%d",&m);
for (int j=0;j<m;j++)
{
scanf("%d %d %d",&a[j],&b[j],&c[j]);
}
while(r-l>1e-8)
{
max1=-INFINITY;
max2=-INFINITY;
mid1=l+(r-l)/3.0;
mid2=r-(r-l)/3.0;
for (int j=0;j<m;j++){
ans1=a[j]*mid1*mid1+b[j]*mid1+c[j];
ans2=a[j]*mid2*mid2+b[j]*mid2+c[j];
if (ans1>max1) max1=ans1;
if (ans2>max2) max2=ans2;
}
if (max1>max2) l=mid1;
else r=mid2;
}
max1=-INFINITY;
for (int j=0;j<m;j++)
{
ans1=a[j]*r*r+b[j]*r+c[j];
if (ans1>max1) max1=ans1;
}
printf("%.4lf\n",max1);
}
return 0;
}
3382代码如下:
#include<stdio.h>
#include <math.h>
#define min 1e-6
double com(double a[],double n,int b){
double ans=0;
int tem=b-1;
for (int i=0;i<b;i++){
ans+=a[i]*pow(n,tem--);
}
return ans;
}
int main(){
int n;
double l,r,mid1,mid2;
double a[16];
scanf("%d %lf %lf",&n,&l,&r);
for (int i=0;i<n+1;i++){
scanf("%lf",&a[i]);
}
do
{
mid1=l+(r-l)/3.0;
mid2=r-(r-l)/3.0;
if (com(a,mid1,n+1)<com(a,mid2,n+1)) l=mid1;
else r=mid2;
}while ((r-l)>=min);
printf("%.6lf",l);
return 0;
}
https://www.luogu.com.cn/problem/P3382
两道题都是三分
三分的思路是先确定左边界,和右边界
将这个区间三等分,比较函数值,得出有一部分区间一定不会出现极值
逐渐缩小区间,找到极值。
1883代码如下:
#include<stdio.h>
#include<math.h>
int a[10010], b[10010], c[10010];
double l=0,r=1000,mid1,mid2;
double max1=-INFINITY,max2=-INFINITY,ans1,ans2;
int main()
{
int n,m;
scanf("%d",&n);
for (int i=0;i<n;i++)
{
l=0;
r=1000;
max1=-INFINITY;
max2=-INFINITY;
scanf("%d",&m);
for (int j=0;j<m;j++)
{
scanf("%d %d %d",&a[j],&b[j],&c[j]);
}
while(r-l>1e-8)
{
max1=-INFINITY;
max2=-INFINITY;
mid1=l+(r-l)/3.0;
mid2=r-(r-l)/3.0;
for (int j=0;j<m;j++){
ans1=a[j]*mid1*mid1+b[j]*mid1+c[j];
ans2=a[j]*mid2*mid2+b[j]*mid2+c[j];
if (ans1>max1) max1=ans1;
if (ans2>max2) max2=ans2;
}
if (max1>max2) l=mid1;
else r=mid2;
}
max1=-INFINITY;
for (int j=0;j<m;j++)
{
ans1=a[j]*r*r+b[j]*r+c[j];
if (ans1>max1) max1=ans1;
}
printf("%.4lf\n",max1);
}
return 0;
}
3382代码如下:
#include<stdio.h>
#include <math.h>
#define min 1e-6
double com(double a[],double n,int b){
double ans=0;
int tem=b-1;
for (int i=0;i<b;i++){
ans+=a[i]*pow(n,tem--);
}
return ans;
}
int main(){
int n;
double l,r,mid1,mid2;
double a[16];
scanf("%d %lf %lf",&n,&l,&r);
for (int i=0;i<n+1;i++){
scanf("%lf",&a[i]);
}
do
{
mid1=l+(r-l)/3.0;
mid2=r-(r-l)/3.0;
if (com(a,mid1,n+1)<com(a,mid2,n+1)) l=mid1;
else r=mid2;
}while ((r-l)>=min);
printf("%.6lf",l);
return 0;
}
全部评论
相关推荐
鑫鑫向栄:爱你,妈咪 点赞 评论 收藏
分享


科大讯飞公司氛围 477人发布