练习cf1920A. Satisfying Constraints

题目如下
A. Satisfying Constraints
time limit per test1 second
memory limit per test256 megabytes
Alex is solving a problem. He has 𝑛 constraints on what the integer 𝑘 can be. There are three types of constraints:

𝑘 must be greater than or equal to some integer 𝑥;
𝑘 must be less than or equal to some integer 𝑥;
𝑘 must be not equal to some integer 𝑥.
Help Alex find the number of integers 𝑘 that satisfy all 𝑛 constraints. It is guaranteed that the answer is finite (there exists at least one constraint of type 1 and at least one constraint of type 2). Also, it is guaranteed that no two constraints are the exact same.

Input
Each test consists of multiple test cases. The first line contains a single integer 𝑡 (1≤𝑡≤500) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer 𝑛 (2≤𝑛≤100) — the number of constraints.

The following 𝑛 lines describe the constraints. Each line contains two integers 𝑎 and 𝑥 (𝑎∈{1,2,3},1≤𝑥≤109). 𝑎 denotes the type of constraint. If 𝑎=1, 𝑘 must be greater than or equal to 𝑥. If 𝑎=2, 𝑘 must be less than or equal to 𝑥. If 𝑎=3, 𝑘 must be not equal to 𝑥.

It is guaranteed that there is a finite amount of integers satisfying all 𝑛 constraints (there exists at least one constraint of type 1 and at least one constraint of type 2). It is also guaranteed that no two constraints are the exact same (in other words, all pairs (𝑎,𝑥) are distinct).

Output
For each test case, output a single integer — the number of integers 𝑘 that satisfy all 𝑛 constraints.

题目大意
找出符合条件的数的数量,每组样例有n个条件来缩小数的范围,有三种类型,分别是1,要求x>=k; 2,要求x<=k; 3,要求x!=k。
经过n次筛选后,输出剩余的符合条件的数的数量。

题目分析
先给定数的最大范围,再根据每次的限制1,2修改边界,最后再根据3的要求减去对应的数。
通过边界的差值以及条件3的约束获得最后的数量。

代码如下

点击查看代码
#include <iostream>
using namespace std;

int main(){
    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;
        int L = 1, R = 1e9;
        int nums[100];
        int cnt = 0;
        for(int i = 0; i < n; i++){
            int type, num;
            cin >> type >> num;
            if(type == 1){
                L = max(L, num);
            }else if(type == 2){
                R = min(R, num);
            }else if(type == 3){
                nums[cnt++] = num;
            }
        }
        if(L > R){
            cout << 0 << endl;
            continue;
        }
        int ans = R - L + 1;
        for(int i = 0; i < cnt; i++){
            if(nums[i] >= L && nums[i] <= R){
                ans--;
            }
        }
        cout << ans << endl;
    }
    return 0;
}
posted @ 2025-08-06 21:24  sirro1uta  阅读(8)  评论(0)    收藏  举报