Codeforces Problem 778B 拆位做法

来源:互联网 发布:c语言中的float 编辑:程序博客网 时间:2024/06/06 12:40

题目: http://codeforces.com/problemset/problem/778/B

简述题意

有n条语句,每一句描述一个变量名,以及其值(二进制),或表达式(仅由前面的变量名、"?"、运算符号组成)我们的任务是:求出是所有变量最大 || 最小的“?”

分析

二进制。。。我们可以使用拆位,即每一位分开处理先读入,预处理循环一次所有语句,同时循环每一位,尝试该位为0或1,然后按要求得出答案

另外

这道题的难点应该在于字符串处理。。。

贴代码

#include<cstdio>#include<iostream>#include<string>#include<map>using namespace std;const int maxn = 5050;const int maxm = 1050;map<string, int> name;bool val[maxn][maxm];int oper[maxn];string x[maxn], y[maxn];int n, m;string s, ans_min="", ans_max="";int cal(int a, int b) {    int g[maxn], x0, y0, ans = 0;    for(int i = 1; i <= n; i++) {        if(oper[i] == 0) ans += g[i] = val[i][a];        else {            x0 = x[i] == "?" ? b : g[name[x[i]]];            y0 = y[i] == "?" ? b : g[name[y[i]]];            if(oper[i] == 1) ans += g[i] = x0 & y0;            if(oper[i] == 2) ans += g[i] = x0 | y0;            if(oper[i] == 3) ans += g[i] = x0 ^ y0;        }    }    return ans;}int main() {    cin >> n >> m;    for(int i = 1; i <= n; i++) {        cin >> s;        name[s] = i;        cin >> s >> s;        if(s[0] == '0' || s[0] == '1') {            oper[i] = 0;            for(int j = 0; j < m; j++) val[i][j] = s[j] - '0';        }        else {            x[i] = s;            cin >> s;             oper[i] = s == "AND" ? 1 : (s == "OR" ? 2 : 3);            cin >> s;            y[i] = s;        }    }    for(int i = 0; i < m; i++) {        int k0, k1;        k0 = cal(i, 0);        k1 = cal(i, 1);        if(k0 <= k1) ans_min += '0'; else ans_min += '1';        if(k0 >= k1) ans_max += '0'; else ans_max += '1';    }    cout << ans_min << endl << ans_max << endl;    return 0;}
0 0
原创粉丝点击