B. Numbers on the Chessboard -codeforces1027 -csdn博客

You are given a chessboard of size n×n. It is filled with numbers from 1 to n2 in the following way: the first ⌈n22⌉ numbers from 1 to ⌈n22⌉ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest n2−⌈n22⌉ numbers from ⌈n22⌉+1 to n2 are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation ⌈xy⌉ means division x by y rounded up.

For example, the left board on the following picture is the chessboard which is given for n=4 and the right board is the chessboard which is given for n=5.
这里写图片描述
You are given q queries. The i-th query is described as a pair xi,yi. The answer to the i-th query is the number written in the cell xi,yi (xi is the row, yi is the column). Rows and columns are numbered from 1 to n.

Input
The first line contains two integers n and q (1≤n≤109, 1≤q≤105) — the size of the board and the number of queries.

The next q lines contain two integers each. The i-th line contains two integers xi,yi (1≤xi,yi≤n) — description of the i-th query.

Output
For each query from 1 to q print the answer to this query. The answer to the i-th query is the number written in the cell xi,yi (xi is the row, yi is the column). Rows and columns are numbered from 1 to n. Queries are numbered from 1 to q in order of the input.
Examples
inputCopy
4 5
1 1
4 4
4 3
3 2
2 4
outputCopy
1
8
16
13
4
inputCopy
5 4
2 1
4 2
3 3
3 4
outputCopy
16
9
7
20
Note
Answers to the queries from examples are on the board in the picture from the problem statement.

  • 题意:给你一个n×n的方框,在里面根据规则填数字,有q个查询,输出每个查询x,y对应位置数字大小。
    规则:行和列之和为偶数是,数字为前n^2/2(上限),顺序从左到右,从上倒下,如果为奇数,则为n^2/2+1到n^2;

  • 题解:首先判断行和列之和奇偶行,如果是奇数,那么加上n^2/2(如果n^2为奇数,那么要加上1)。然后就是你恶不的判断了。我们首先可以判定如果行满足是两行连续时,那么一共有n个数填了进去,因此我用(a-1)/2看看满足的有多少个满两行对。具体操作如下。
    关于这个题的解法大家可以自己画图试一试,找一找为什么要这样写

#include<bits/stdc++.h>
#define endl '\n'
#define pb push_back
#define mp make_pair
#define _ ios::sync_with_stdio(false)
bool SUBMIT = 1;
typedef long long ll;
using namespace std;
const double PI = acos(-1);
ll n,q;
int main()
{
    if(!SUBMIT)freopen("i.txt","r",stdin);else _;
    cin>>n>>q;
    for(ll i=0;i<q;i++)
    {
        ll a,b;cin>>a>>b;
        ll c;
        if(n*n%2)c=n*n/2+1;
        else c=n*n/2;
        ll ans=0;
        if(a>2)
            ans+=n*((a-1)/2);
        a-=(a-1)/2*2;
        if(a>1)ans+=n/2;
        if((a+b)%2){
            //if(a>1&&n%2)ans++;//此时不用这句话,因为奇数的话加在了前n^2/2内
            ans+=(b+1)/2;
            ans+=c;
        }else
        {
            if(a>1&&n%2)ans++;//必须有,n为奇数且前半部分的话,每对第一行还要多一个数
            ans+=(b+1)/2;
        }
        cout<<ans<<endl;
    }
    return 0;
}

欢迎欢迎,如果大家喜欢的话可以关注一波O(∩_∩)O哈哈~

猜你喜欢

转载自blog.csdn.net/qq_38701476/article/details/81837485