hihocoder 1341 Constraint Checker【string】

本文介绍了一种用于验证一系列不等式的算法实现。通过解析输入的不等式字符串,将其拆分为具体的数值比较操作,并利用C++编程语言进行实现。最终能够判断一组数据是否满足所有给定的不等式条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

hihocoder 1341

解释:
这道题题目还是比较容易理解,就是根据输入的若干个不等式,校验后面输入的数据是否都满足前面的不等式,满足就输出Yes,只要有一个不满足就输出No。如“A<B<=E,3<=E<5”这个两个关系式,对于输入A=1,B=2,E=3肯定满足,因为1<2<=3,3<=3<5。而A=3, B=5,E=10就不满足,因为3<=10<5不成立。

思路:

将一串表达式拆分为每两个数比较大小,读取操作数[字母/数字], 读取运算符[‘<’/‘<=’]

#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <string.h>
#include <ctype.h>
using namespace std;

map<char,int> mp;

string c[20];
bool used[26];

bool ok(int a, string &op, int b){
    if(op=="<") return a<b;
    return a<=b;
}

int get_val(string &s, int &i){
    int res=0;
    for(; s[i] && isdigit(s[i]) && !isalpha(s[i]); res*=10, res+=s[i++]-'0');
    if(isalpha(s[i])) res=mp[s[i++]];
    return res;
}

string get_op(string &s, int &i){
    string res;
    for(; s[i] && ispunct(s[i]); res+=s[i++]);
    return res;
}

bool check(int n){
    int a, b;
    string op;
    for(int i=0; i<n; i++){
        int j=0;
        a=get_val(c[i], j);
        for(;;){
            op=get_op(c[i], j);
            if(op=="") break;
            b=get_val(c[i], j);
            if(!ok(a, op, b)) return false;
            a=b;
        }
    }
    return true;
}

int main(){
    int n, T;
    cin>>n;
    for(int i=0; i<n; i++){
        cin>>c[i];
        for(auto x:c[i])
            if(isalpha(x)) used[x-'A']=true;
    }
    int nv=0;
    for(int i=0; i<26; i++) nv+=used[i];
    
    for(cin>>T; T--; ){
        for(int i=0; i<nv; i++){
            char x;
            int v;
            cin>>x>>v;
            mp[x]=v;
        }
        puts(check(n)?"Yes":"No");
    }
}

转载于:https://www.cnblogs.com/demian/p/6533717.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值