資源限制
時間限制:1.0s 內存限制:256.0MB
問題描述
《審美的歷程》課上有n位學生,帥老師展示了m幅畫,其中有些是梵高的作品,另外的都出自五歲小朋友之手。老師請同學們分辨哪些畫的作者是梵高,但是老師自己並沒有答案,因爲這些畫看上去都像是小朋友畫的……老師只想知道,有多少對同學給出的答案完全相反,這樣他就可以用這個數據去揭穿披着皇帝新衣的抽象藝術了(支持帥老師_)。
答案完全相反是指對每一幅畫的判斷都相反。
輸入格式
第一行兩個數n和m,表示學生數和圖畫數;
接下來是一個n*m的01矩陣A:
如果aij=0,表示學生i覺得第j幅畫是小朋友畫的;
如果aij=1,表示學生i覺得第j幅畫是梵高畫的。
輸出格式
輸出一個數ans:表示有多少對同學的答案完全相反。
樣例輸入
3 2
1 0
0 1
1 0
樣例輸出
2
樣例說明
同學1和同學2的答案完全相反;
同學2和同學3的答案完全相反;
所以答案是2。
數據規模和約定
對於50%的數據:n<=1000;
對於80%的數據:n<=10000;
對於100%的數據:n<=50000,m<=20。
將每個人的判斷看出是二進制的字符串,然後使用HashMap進行存儲,完全相反的判斷即是對這個二進制字符串進行取反
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
// 這裏不要用到m這個數據,所以不保存
Reader.nextInt();
// 創建一個大小爲10000的map用來存儲每個人的判斷
Map<String, Node> map = new HashMap<String, Node>(10000);
for (int i = 0; i < n; i++) {
String s = Reader.nextLine();
s = s.replaceAll(" ", "");
// 把判斷完全相同的人劃分到一起
if (!map.containsKey(s)) {
Node node = new Node();
map.put(s, node);
} else {
Node node = map.get(s);
node.num++;
}
}
int sum = 0;
for (String key : map.keySet()) {
// 對每個字符取反,即完全不相同的判斷結果
char[] chs = key.toCharArray();
for (int i = 0; i < chs.length; i++) {
chs[i] = chs[i] == '1' ? '0' : '1';
}
String _key = new String(chs);
Node node = map.get(_key);
// 判斷是否有完全不相同的判斷,有則計算有幾對人
if (node != null) {
sum += map.get(key).num * node.num;
}
}
// 上面計算了2次,所以需要除以2
System.out.println(sum/2);
}
}
class Node {
int num = 1;
}
// 下面不是邏輯代碼,只是輸入模板,加入讀取數據的速度
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
// ** call this method to initialize reader for InputStream *//*
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
// ** get next word *//*
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static char nextChar() throws IOException {
return next().toCharArray()[0];
}
static float nextFloat() throws IOException {
return Float.parseFloat(next());
}
static Double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}