【hackerrank week of code 26】Hard Homework
【题目链接】:https://www.hackerrank.com/contests/w26/challenges/hard-homework/problem
【题意】
给你一个式子:sin(x)+sin(y)+sin(z)
这里x,y,z都为正整数;
让你求这个式子的最大值;
【题解】
由和差化积公式;
这里枚举x+y从2到n-1
x-y不好处理;
但如果我们分步来做;
对于x+y为偶数的情况;
我们每次从x+y推到x+y+2
会发现x-y的值每次会增加两个即|x+y-2|和-|x+y-2|
比如
①
x+y=2
x=1,y=1
则x-y
{0}
②
x+y=4
x=2,y=2 && x=1,y=3
{0}{-2}{2}
③
x+y=6
x=3,y=3 && x=4,y=2 && x= 5,y=1
{0}{2}{4}{-4};
且因为cos(-x)=cos(x)
所以每次x-y只用计算一个x+y-2即可;
然后把cos((x-y)/2)的最大值和最小值都带进去算一下就好了;
【Number Of WA】
WA > 4
【反思】
得到公式了,但对x-y这一点没有处理好;
没能得到x-y随x+y的变化规律.
还是偷懒了吧,没有多试几个x+y变化一下.
好像有试,但是只是试了+1的情况,觉得麻烦了,没往分类那里想。
【完整代码】
#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)
#define Open() freopen("F:\\rush.txt","r",stdin)
#define Close() ios::sync_with_stdio(0)
typedef pair<int,int> pii;
typedef pair<LL,LL> pll;
const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 110;
int n;
double mi = 1e8,ma = -1e8,ans = -4;
int main(){
//Open();
Close();
cin >> n;
for (int i = 2;i <= n-1;i+=2){
double xsy = i-2;
mi = min(mi,cos(xsy/2.0));
ma = max(ma,cos(xsy/2.0));
ans = max(ans,2*sin(i/2.0)*mi+sin(n-i));
ans = max(ans,2*sin(i/2.0)*ma+sin(n-i));
}
mi = 1e8,ma = -1e8;
for (int i = 3;i <= n-1;i+=2){
double xsy = i-2;
mi = min(mi,cos(xsy/2.0));
ma = max(ma,cos(xsy/2.0));
ans = max(ans,2*sin(i/2.0)*mi+sin(n-i));
ans = max(ans,2*sin(i/2.0)*ma+sin(n-i));
}
cout << fixed << setprecision(9) << ans << endl;
return 0;
}