1. 寻找循环最小子串
- 输入一个字符串,判断改字符串是否是完全循环,如果循环,则输出最短循环子串;反之输出自身;
- 循环:输入
abababab
,输出最短循环子串:ab
- 不循环:输入:
abc
,输出:abc
留着吃了饭写
2. 快速幂实现计算器
- 实现加法:
1 2 +
,输出:3
- 实现减法:
1 2 -
,输出:-1
- 实现乘法:
1 3 *
,输出:3
- 实现幂运算:
2 3 ^
,输出:8
注:结果需要对1e9 + 7
取模
这个题主要就用快速幂实现幂运算,然后就是乘法可能会溢出,所以需要使用long long
类型并进行取模:
快速幂:
参考数值的整数次方
#include <iostream>
using namespace std;
const int M = 1e9 + 7;
// 定义加法运算 add
long long add(long long a, long long b) { return (a + b) % M; }
// 定义减法运算 sub
long long sub(long longa, long longb) { return (a - b) % M; }
// 定义乘法运算
long long mul(long long a, long long b) { return ((a % M) * (b % M)) % M; }
// 定义幂运算——快速幂
long long myPow(long long a, long long b){
long long res = 1, tmp = a;
while(b != 0){
if((b & 1) != 0){
res *= tmp;
res %= M;
}
tmp *= tmp;
tmp %= M;
b >> 1;
}
return res;
}
int main(){
int N;
cin >> N;
for(int i = 0; i < N; ++ i){
int a, b;
char opt;
cin >> a >> b >> opt;
// 题目好像是保证了输入合法,即操作只包括'+'、'-'、'*'、'^'
if(opt == '+') cout << add(a, b) << endl;
else if(opt == '-') cout << sub(a, b) << endl;
else if(opt == '*') cout << mul(a, b) << endl;
else cout << myPow(a, b) << endl;
}
return 0;
}
3. 计算曼哈顿距离的最小
- 输入:
M
和N
表示有M
个人的坐标,N
个车站的坐标;- 接下来
M
行表示每个人的坐标(x, y
),N
行表示每个车站坐标(p_x, p_y
);- 每个车站与人的距离采用曼哈顿距离计算;
- 输出:距离所有人的距离最短的车站坐标(有重复的输出第一次出现的)
暴力法,超时
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<float> > people(n, vector<float>(2, 0));
vector<vector<float> > station(m, vector<float>(2, 0));
vector<float> res(m, 0);
for (int i = 0; i < n; ++i) {
float x, y;
cin >> x >> y;
people[i][0] = x, people[i][1] = y;
}
for (int j = 0; j < m; ++j) {
float x, y;
cin >> x >> y;
station[j][0] = x, station[j][1] = y;
for (int i = 0; i < n; ++i) {
float xx = abs(x - people[i][0]);
float yy = abs(y - people[i][1]);
float dist = xx + yy;
res[j] += dist;
}
}
float min = INT_MAX;
int index;
for (int i = 0; i < res.size(); ++i) {
if (res[i] < min) {
index = i;
min = res[i];
}
}
cout << station[index][0] << " " << station[index][1] << endl;
return 0;
}
4. 完美树
不是很懂题的意思 哈哈哈哈