先将字符串中的数字提取出来,三种运算进行dfs,用栈存储运算符号,达到终点输出。
string s;
char c[20]; //符号-相当于栈的操作
int c1;
long long a[20]; //运算的数
int a1;
typedef long long ll;
ll quickPower(ll a, ll b, ll p) { //快速幂
ll sum = 1;
a %= p;
while (b > 0) {
if (b % 2) { //(b&1)
sum *= a;
sum %= p;
} //a^b化为(a*a)^(b/2)
a *= a;
a %= p;
b /= 2; //(b>>=1)
}
return sum;
}
void fun1(int x,ll& ans) { //+
ans += a[x + 1];
}
void fun2(int x, ll& ans) { //-
ans -= a[x + 1];
}
void fun3(int x, ll& ans) { //#
ans = quickPower(ans, ans, a[x + 1]);
}
void fun() { //提取数字
ll xx = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
xx *= 10;
xx += s[i] - '0';
}
else {
a[a1++] = xx;
xx = 0;
}
if (i == s.size() - 1) {
a[a1++] = xx;
}
}
}
int dfs(int x,ll ans) { //x为当前已操作的数的下标,ans为左式结果
if (c[c1] == '=') { //终点
if (ans == a[a1 - 1]) {
for (int i = 0; i < a1; i++) {
cout << a[i];
if (i == a1 - 1)break;
if (i < c1)cout << c[i];
else cout << '=';
}cout << '\n';
return 1;
}
else return 0;
}
for (int i = 1; i <= 3; i++) {
if (i == 1) { //加法
long long ans1 = ans;
fun1(x,ans);
c[c1++] = '+';
if (dfs(x + 1,ans))return 1;
ans = ans1; //回溯
c1--;
}
else if (i == 2) { //减法
long long ans1 = ans;
fun2(x,ans);
c[c1++] = '-';
if (dfs(x + 1,ans))return 1;
ans = ans1;
c1--;
}
else { //快速幂
if (ans <= 0 || a[x + 1] <= 0)continue;
long long ans1 = ans;
fun3(x,ans);
c[c1++] = '#';
if (dfs(x + 1,ans))return 1;
ans = ans1;
c1--;
}
}
return 0;
}
int main() {
ios::sync_with_stdio(false);
cin >> s;
fun();
c[a1 - 2] = '=';
if (!dfs(0,a[0]))cout << "-1\n";
return 0;
}
给定一个n,可选边长为1-[n/2](向上取整)之间,求正方形最大边长。易得出n=2时无解。先选取最大边d=(n+1)/2组成正方形,后得出若想增加长度,需要再添加3个矩形,可得最终答案为d+(n-d)/3.
void solve() {
long long n;
cin >> n;
if (n == 2) {
cout << "-1\n";
return;
}
long long d = (n + 1) / 2;
long long d1 = (n - d) / 3;
cout << d + d1 << '\n';
}
把x[i]替换为x[i]-t[i],x[i]+t[i],从而把问题简化为有2*n个节点,没有化妆时间,只有x[i]位置的简单问题,答案为(最大+最小)/2.
const int N = 1e5 + 5;
int x[N];
int t[N];
void solve() {
vector<int>a;
int n;
cin >> n;
for (int i = 0; i < n; i++)cin >> x[i];
for (int i = 0; i < n; i++)cin >> t[i];
for (int i = 0; i < n; i++) {
a.push_back(x[i] - t[i]);
a.push_back(x[i] + t[i]);
}
sort(a.begin(), a.end());
int sum = (a[0] + a[2 * n - 1]) / 2;
cout << sum;
if ((a[0] + a[2 * n - 1]) % 2) {
cout << ".5";
}
cout << '\n';
}