样例输入
10 5
2 0.59
2 4.956
1 0.997
1 1.364
1 1.242
1 0.82
2 2.824
1 0.716
2 0.178
2 4.094
1 6 -953188 -946637
1 9 969538 848081
4 7 -114758 522223
1 9 -535079 601597
8 8 159430 -511187
样例输出
-1858706.758 -83259.993
-1261428.46 201113.678
-75099.123 -738950.159
-119179.897 -789457.532
114151.88 -366009.892
分析:
三角函数两角和差公式:
sin(A+B)=sinAcosB+cosAsinB
sin(A-B)=sinAcosB-cossinB
cos(A+B)=cosAcosB-sinAsinB
cos(A-B)=cosAcosB+sinAsinB
tan(A+B)=(tanA+tanB)/(1-tanAtanB)
tan(A-B)=(tanA-tanB)/(1+tanAtanB)
所以拉伸和旋转都可以先综合,再进行变换。
代码示例1:80分,运行超时
#include<iostream>
#include <math.h>
#include<stdio.h>
#include<vector>
using namespace std;
typedef struct {
int k;
double s;//旋转/旋转
}ope;
typedef struct
{
int i;
int j;
long long x;
long long y;
}zub;
int main() {
int n = 0, m = 0;
cin >> n >> m;
vector<ope> onn;
ope temp;
vector<zub> omm;
zub temp0;
int i = 0, j = 0;
for (i = 0; i < n; i++)
{
cin >> temp.k >> temp.s;
onn.push_back(temp);
}
for (i = 0; i < m; i++)
{
cin >> temp0.i >> temp0.j >> temp0.x >> temp0.y;
omm.push_back(temp0);
}
int begin = 0;
int end = 0;
double temp1 = 0;//旋转
double temp2 = 1;//拉伸
for (i = 0; i < m; i++)
{
begin = omm[i].i-1;
end = omm[i].j-1;
for (j = begin; j <= end; j++)
{
if (onn[j].k == 1)
temp2 *= onn[j].s;
else
temp1 += onn[j].s;
}
/*cout << (double)omm[i].x * temp2 * cos(temp1) - omm[i].y * temp2 * sin(temp1) << ' ' <<
(double)omm[i].x * temp2 * sin(temp1) + omm[i].y * temp2 * cos(temp1) << endl;*/
printf("%.3f", omm[i].x * temp2 * cos(temp1) - omm[i].y * temp2 * sin(temp1));
printf(" ");
printf("%.3f", omm[i].x * temp2 * sin(temp1) + omm[i].y * temp2 * cos(temp1));
printf("\n");
temp1 = 0;
temp2 = 1;
}
return 0;
}
1)使用printf函数。这是一个定义在stdio.h或者cstdio头文件中的标准输出函数,它可以使用格式化字符串来控制输出的格式。要保留小数点后几位,可以使用%.nf
的占位符,其中n
是要保留的位数。
2)注意拉伸用的是乘法,所以初始化为1.
优化
代码超时的主要肯定在嵌套for循环,所以对这部分进行研究。
对于连加/连乘,例如,求20-100的和,可以求1-19的和,1-100的和然后相减,乘法同理。
代码示例2:100
CCF-CSP202309-2 坐标变换(其二)-优快云博客
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<vector>
using namespace std;
int main() {
vector<double>la;
vector<double>xu;
la.push_back(1.0);
xu.push_back(0);
int n = 0, m = 0;
cin >> n >> m;
int type = 0;
double value = 0;
int i = 0, j = 0;
for (i = 1; i <= n; i++)
{
cin >> type >> value;
if (type == 1)
{
la.push_back(la[i - 1] * value);
xu.push_back(xu[i - 1]);
}
else {
xu.push_back(xu[i - 1] + value);
la.push_back(la[i - 1]);
}
}
int be = 0, en = 0;
long long x = 0, y = 0;
double temp1 = 1;
double temp2 = 0;
for (i = 0; i < m; i++)
{
cin >> be >> en >> x >> y;
temp1 = la[en] / la[be - 1];
temp2 = xu[en] - xu[be - 1];
printf("%.3f", x * temp1 * cos(temp2) - y * temp1 * sin(temp2));
printf(" ");
printf("%.3f", x * temp1 * sin(temp2) + y * temp1 * cos(temp2));
printf("\n");
}
}