三加二题解

· · 个人记录

题意

若干个连续序列拼接,序列形式为 n 个 1 ,每个 1 左右两边有一个 0 ,共 n + 1 个 0 。\ 给定 T 组数据,每组数据包含 n 和 x ,请问第 x 个元素是 1 还是 0 。\ 数据范围:\ 对于全部测试点:1 \leq T \leq 10^5,0 \leq n \leq 10^{18},1 \leq x \leq 10^{18}\ 对于 30\% 的测试点:1 \leq T \leq 10,0 \leq n \leq 10^6,1 \leq x \leq 10^6

输入样例 #1

3
1 4
0 2
2 7

输出样例 #1

0
0
1

分析

题意很好理解。不难发现每 n \times 2 + 1 次是一个循环,所以我们先对 x 取模 n \times 2 + 1 ,设结果为 k 。\ 然后我们发现当 k = 0 时,对应上一组序列的最后一位,应是 0 ;否则,应是 k \bmod 2 ,对应这组序列的 1 到 n \times 2 位。\ 上述为第一种方法,对应下文中参考代码a。\ 为了防止 k = 0 时对应上一组序列,我们可以使得 k = (x - 1) \bmod (n \times 2 + 1) 。此时答案为 k \bmod 2 。\ 上述为第二种方法,对应下文中参考代码b。\ 此外,本题还有许多种换汤不换药的实现办法。本文不再介绍。\ 由于本题数据范围,应选择合适的数据类型。

代码

参考代码a

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
int t,n,x;
signed main(){
    cin >> t;
    while (t--){
        cin >> n >> x;
        x = x % (2 * n + 1);
        if (x == 0) cout << 0;
        else cout << (x + 1) % 2;
        cout << "\n";
    }
    return 0;
}

参考代码b

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
int t;
int n,x;
signed main(){
    cin >> t;
    while (t--){
        cin >> n >> x;
        cout << (x-1) % (n * 2 + 1) % 2<< endl; 
    } 
    return 0;
}