java题解,注释版。
题目:
链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
题目描述
Tongtong is playing math game again. She had come across this square matrix many times,so needless to say, she knows what you want to ask. Now she throws this question to you. You need to look at the following square matrix,then she will give you three integers n,x,and y,that means there are an n×n square matrix.
You need to figure out what the value of row x, column y corresponds to.
For example,there are one 5×5 square matrix:
0 1 3 6 A
2 4 7 B F
5 8 C 10 13
9 D 11 14 16
E 12 15 17 18
输入描述:
Only a single line contains three integers n,x,y (0≤x≤1000000000, 0≤y≤1000000000, 1≤n≤1000000001)
输出描述:
A single line with an integer representing the corresponding value.
示例1
输入
复制5 2 2
5 2 2
输出
复制12
12
简单的说就是找到方阵的规律,然后取出对应的值。
规律很简单,第一行的值是y坐标的累加,例:(0,0)=0 --> 0
(0,1) =1 --> 0+1
(0,2) =3 --> 0+1+2
然后反斜列(右上-左下)递增(左上部分)
转化方式为y坐标加上x坐标,然后根据第一行对应y坐标的值加上x(x是几就说明移动了几个,就应该加上几);
右下部分规律,右下角的点的值是n*n-1(点数减一,因为是从0开始计数的)
然后最下一行的值是右下角点减去(n-1-y)的累加,例:(4,3)=24-(5-1-3)= 23
(4,2)=24 - ((5-1-3)+(5-1-2))=21
转化规律是y坐标加上(n-1-x)对应y坐标的值加上(n-1-x),与上方同理。
import java.util.*;
public class Main{
public static void main(String args[]){
long n=5, x=3, y=4;
long t=0;
Scanner sc = new Scanner(System.in);
n = sc.nextLong();
x = sc.nextLong();
y = sc.nextLong();
if(x+y<n){
t=(x+y)*(x+y+1)/2;
t+=x;
System.out.println(t);
}else{
t=(n*n)-1-(n-1-(y-n+1+x))*(n-(y-n+1+x))/2-(n-1-x);
System.out.println(t);
}
}
}
以上算式故意没有化简,就是为了能看懂过程,可以自行化解。