acwing52周赛
1.智力测试
算法(暴力枚举) \(O(n)\)
枚举即可,直到大于所给值就退出,并且减一即为答案。
C++ 代码
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e5 + 10;
int n, m, k;
int main()
{
cin >> n;
int cnt = 0, i = 0;
while(1)
{
cnt += i * (i + 1) /2;
if(cnt > n)
break;
i++;
}
cout << i - 1;
return 0;
}
2.最近距离
算法(模拟) \(O(n)\)
题目大意让我们找数组中每一个元素与数组中最近为0的元素的最小距离,我们可以先将0预处理出来,后直接判断即可。
C++ 代码
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e6 + 10;
int n, m, k;
int a[N];
vector<int> b;
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
if(a[i] == 0)
b.push_back(i);
}
int cnt = 0;
for(int i = 1; i <= n; i++)
{
if(a[i] == 0)
{
cout << 0 << " ";
cnt++;
continue;
}
if(i >= b[cnt])
{
if(cnt == b.size())
cout<< i - b[cnt - 1] << " ";
else
{
if(i <= (b[cnt] + b[cnt + 1] >> 1))
cout << abs(i - b[cnt]) << " ";
else
cout << abs(i - b[cnt + 1]) << " ";
}
}
else
{
if(cnt - 1 == -1)
cout << abs(i - b[cnt]) << " ";
else
{
if(i <= (b[cnt] + b[cnt - 1] >> 1))
cout << abs(i - b[cnt - 1]) << " ";
else
cout << abs(i - b[cnt]) << " ";
}
}
}
return 0;
}
3.等式
算法(数学知识) \(O(n)\)
给定一个非负整数 d,请你找到两个非负实数 a,b,使得等式 a+b=d 和 a×b=d 同时成立。
我们把先将\(a = d - b\),代入得到\(b^2 - db + d = 0\),我们就是求一元二次方程的解即可。
时间复杂度
一次遍历即可求出 \(O(n)\)
C++代码
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int t;
int main()
{
cin >> t;
while(t--)
{
double x;
cin >> x;
double c = x * x - 4 * x;
if(c < 0)
printf("N\n");
else
{
double x1 = (x + sqrt(c)) / 2.0;
double x2 = (x - sqrt(c)) / 2.0;
printf("Y %.10f %.10f\n", x1, x2);
}
}
return 0;
}