复习总结提高版 – 递归解法
#include <stdio.h>
#include <stdlib.h>
#define not !
#define and &&
#define or ||
#define ri register int
#define rep(inc, frm, to) for (ri inc = frm; inc < (to); ++inc)
#define rep2(inc, frm, to) for (ri inc = frm; inc > (to); --inc)
#define r() fast_read()
typedef long long int ll;
ll fast_read(void) {
ll n = 0, sign = 1;
char c = getchar();
while (c < 48 or c > 57) {
if (c == '-') sign = ~0;
c = getchar();
}
while (c >= 48 and c <= 57) {
n = (n << 1) + (n << 3) + (c ^ 48);
c = getchar();
}
return sign * n;
}
// 数学归纳法
int solve(int n, int y, int x) {
if (y == 1) return x;
if (x == n) return n - 1 + y;
if (y == n) return 3 * n - 1 - x;
if (x == 1) return 4 * n - 2 - y;
return 4 * (n - 1) + solve(n - 2, y - 1, x - 1);
}
signed main(int argc, char const *argv[]) {
int n = r(), y = r(), x = r();
printf("%d\n", solve(n, y, x));
return ~~(0 ^ 0);
}
没有什么算法思想。。。计算的底功还是有的,算不出硬算!!
#include <iostream>
using namespace std;
int n, i, j;
int main(void) {
scanf("%d %d %d", &n, &i, &j);
int left = j, right = n - j + 1, top = i, bottom = n - i + 1;
int l = min(left, min(right, min(top, bottom)));
int ans = 1, r = l, c = l;
for (int i = 1; i < l; ++i) {
ans += 4 * (n - 1); // 第l层左上角的第一个数为ans
n -= 2; // 第l层的子矩阵大小减少2
}
// 接下来分四种情况讨论
if (i == r) // 子矩阵第一行
ans += j - c;
else if (j == c + n - 1) // 子矩阵最后一列
ans += n - 1 + i - r;
else if (i == r + n - 1) // 子矩阵最后一行
ans += 2 * (n - 1) + (n - 1 - (j - c));
else if (j == c) // 子矩阵第一列
ans += 3 * (n - 1) + (n - 1 - (i - r));
printf("%d\n", ans);
}