蛇形数阵 题解
题目背景
小S最近迷上了蛇形矩阵。蛇形矩阵的生成方式为:从矩阵的左上角(第 1 行第 1 列)出发,初始时向右移动一格,然后向左下移动,直到碰到边界;如果下方是在范围内未出界的格子,则向下移动一格接着往右上移动,否则向右移动一格接着往右上移动,直到到达边界;接着,如果右边的格子在范围内,往右移动一格,否则向下移动一格,接着往左下直到边界;重复上述操作直至经过矩阵中所有格子。
就像这样
将1~15放进一个
这样我们就求出了坐标。类似求这一行有多少个数字,我们也可以
LL calc(LL x) {
LL all;
if (x < min(n, m))
all = x * (x + 1) / 2;
else if (n + m - x < min(n, m))
all = n * m - (n + m - 1 - x) * (n + m - x) / 2;
else
all = x * min(m, n) - min(m, n) * (min(m, n) - 1) / 2;
return all;
}
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#define RI register int
#define LL long long
using namespace std;
LL n, m, l, r;
LL calc(LL x) {
LL all;
if (x < min(n, m))
all = x * (x + 1) / 2;
else if (n + m - x < min(n, m))
all = n * m - (n + m - 1 - x) * (n + m - x) / 2;
else
all = x * min(m, n) - min(m, n) * (min(m, n) - 1) / 2;
return all;
}
LL fun(LL x){
LL i,t,c,p=0,o;
for(i=1;i<=18;i++){
p+=9*pow(10,i-1)*i;
if(p>=x)break;
}
c=i-1;
t=pow(10,c)+(x-1-p+9*pow(10,i-1)*i)/i;
for(i=int(x-p+9*pow(10,i-1)*i-1)%i+1;i<=c;i++)t/=10;
return t%10;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
cin >> n >> m >> l >> r;
LL x = l + r - 1;
LL g = calc(x - 1);
LL y = (r - l + x - 1) / 2 + 1;
if (x > n)
y -= x - n;
//printf("%lld\n", g);
LL h;
if (x < min(m, n))
h = x;
else if (n + m - x < min(n, m))
h = n + m - x;
else h = min(n, m);
//printf("%lld\n", h);
if (x % 2 == 0) {
y = h - y + 1;
}
LL t = g + y;
//printf("%lld %lld\n", x, y);
printf("%lld\n", fun(t));
/*LL p = 1, q = 9, r, ct =0, now = 0;
while (1) {
if (now + p * q >= t) {
g = (t - now - 1) / p + ct + 1;
r = (t - now) % p;
for (LL k = 1;k <= r; ++k)
g /= 10;
cout << g % 10 << endl;
break;
}
now += q * p;
ct += q;
++p;
q *= 10;
}*/
}
return 0;
}