【发布时间】:2019-11-26 12:45:04
【问题描述】:
问题来了。在游戏中,有一个长方形的硬币网格,正面=1,反面=0。游戏有一个简单的规则:玩家不能抛一枚硬币,而是可以选择一行(或一列)同时翻转该行(或该列)中的所有硬币。游戏的目标是找出一种翻转硬币的策略,以使正面硬币的数量最大化。第一个输入值是行 >> 然后是列 >> 和硬币
Sample inputs:
5 4
1010
0101
1010
1010
1010 //Sample output of this: 20
5 4
0010
1101
0110
0110
1011 //Sample output of this: 17
我用'0'和'1'的计数方法完成了我的代码,如果零更多,则切换它。这种方法只通过了简单的测试用例,但是当它进入困难的测试用例时,它失败了,因为有些情况需要多次推特。我想不出另一种更好的方法来处理它。
这是我的代码:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
bool ConeIsMore(vector <vector<char> > table, int size, int j) {
int countzero = 0;
int countone = 0;
for (int i = 0; i < size; i++) {
(table[i][j] == '0')?++countzero: ++countone;
}
if (countone >= countzero) {
return true;
}
return false;
}
bool RoneIsMore(vector <vector<char> > table, int size, int i) {
int countzero = 0;
int countone = 0;
for (int j = 0; j < size; j++) {
(table[i][j] == '0') ? ++countzero : ++countone;
}
if (countone >= countzero) {
return true;
}
return false;
}
int main() {
//Initialise row and column
int row;
int column;
while (cin >> row >> column) {
//Initiallise 2D vector
vector <vector<char> > table(row, vector<char>(column));
//get each digit of number and store it into number
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
cin >> table[i][j];
}
}
//check for column
for (int j = 0; j < column; j++) {
if (!ConeIsMore(table, row, j)) {
for (int i = 0; i < row; i++) {
(table[i][j] == '0') ? table[i][j] = '1' : table[i][j] = '0';
}
}
}
//check for row
for (int j = 0; j < row; j++) {
if (!RoneIsMore(table, column, j)) {
for (int i = 0; i < column; i++) {
(table[j][i] == '0') ? table[j][i] = '1' : table[j][i] = '0';
}
}
}
//Count One in the table
int ans = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
(table[i][j] == '1') ? (ans++) : (ans = ans);
}
}
cout << ans << endl;
}
return 0;
}
当我研究测试用例时,我发现有一些需要检查各种时间,这让我觉得我的方法不是一个好方法。任何人都可以提出更好的处理方法吗?非常感谢。
以下是更难的测试用例:
5 4
0010
1101
0110
0110
1011 //17
5 4
0110
1111
0101
0110
0100 //16
5 4
0110
1001
0011
1110
1000 //16
5 4
1100
0001
1111
0101
1010 //16
5 4
0101
0110
1001
1000
0011 //16
5 4
0111
1100
0100
1000
1011 //16
5 4
1101
1110
0111
1011
0111 //15
5 4
1100
1001
0110
1001
1000 //17
【问题讨论】:
-
据我所知,这是一个算法问题,而不是一个编程问题。在完成算法之前,您不应该开始编写代码。请提供更难的测试用例
-
@ChristiePPP 作为旁注,我猜你误解了三元运算符的使用。
-
@Moia 是不是三元运算符指的是(语句)?(真表达式):(假表达式);
-
@ThomasSablik 我最初认为的方法是为列切换一次,为行切换一次以获得结果,因为我得到的原始测试用例是我可以实现这种愚蠢方法的简单测试用例跨度>
-
我认为@Moia 指的是您使用三元运算符作为 if 语句,而忽略了它是一个实际返回值的表达式(您可以这样做;您的代码有效)。例如:
(test) ? A = 1: A = 2;也可以写成A = (test) ? 1 : 2;,这样更符合运营商的预期用途。
标签: c++ algorithm char structure coin-flipping