您的位置:首页 > 运维架构

Topcoder SRM Div2 Level2

2013-06-24 21:04 561 查看
题目: http://community.topcoder.com/stat?c=problem_statement&pm=12399&rd=15489
题目大意:运算O是三种位运算&,||和^之一; 求需要至少多少种输入才能判定O是哪种运算?

 

解题报告:http://apps.topcoder.com/wiki/display/tc/SRM+569

A non-simulation approach that is faster and needs less code simply requires to analyze the binary operations. Let us make
truth tables for the possible operations.

xyx&yx|yx^y
00000
01011
10011
11110
 

This is interesting, if for example, both x and y were 0, they would not be useful at differentiating between the operations, because they all return 0 in that case.

If we had x=1, y=0 or vice versa, then we can differentiate between x&y and the others. We would not be able to distinguish between XOR and OR though.

If we had both x=1 and y=1, then we would be able to identify the XOR operation, but not the others.

We need both cases, a case in which x and y are different and a case in which they are both 1 to be able to completely distinguish between the three operations. Note that we cannot use a single plate for both inputs, this
means that we need two plates that have a 1 bit in the current bit position and we also need another plate that has a 0 in this position. As long as the condition is true, we can differentiate between the circuits. The approach is then to just count the number
of plates with 1 and 0 in that bit position, if there are at least two 1s and one 0, then it is possible.

从真值表中可以看到, 1和0 可以判定与运算和或运算, 1和1可以判定异或运算。那么判断三种运算必须需要输入1,1,0. 即1的个数大于2, 0 的个数大于1.

Code

class TheDeviceDiv2
{
public string identify(string[] plates)
{
return CanIdentify(plates) ? "YES" : "NO";
}

private static bool CanIdentify(string[] plates)
{
if (plates.Length <= 1)
{
return false;
}

int m = plates[0].Length;
for (int i = 0; i < m; i++)
{
int one = 0;
int zero = 0;
foreach (string plate in plates)
{
if (plate[i] == '1')
{
one++;
}
else
{
zero++;
}
}

if (one < 2 || zero < 1)
{
return false;
}

}
return true;
}

}


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  TopCoder 位运算