输入样例:
3 4
4 1 2 3
4 1 3 2
4 2 1 3
输出样例:
4
样例解释
一致的奶牛对为 (1,4)、(2,4)、(3,4)、(1,3)。
解题思路:
方法一:用递归实现组合型枚举,找出所有可能的奶牛对数,再依次对每一对奶牛进行校验,找出它们在每行的相对位置,并对符合条件的情况计数。
方法二:题目中给出的数组,以一行为例,arr[i] = j : 表示第i名的位置是第j名奶牛。转化为loc[j] = i: 表示第j名奶牛所在的排列位置是第i个。由于二维数组的每一列都表示 每一头奶牛在各行的排位,所以只需要比较两两奶牛的排位即可。
Java代码一:(递归搜索对数)
import java.io.*;
public class Main {
static int n;
static int count;
static int[]state = new int[3];
static int [][]couple = new int[200][2];//存放对数(考虑顺序)
static int [][]arr;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] split = br.readLine().split(" ");
int k = Integer.parseInt(split[0]);
n = Integer.parseInt(split[1]);
arr = new int[k][n];
for(int i = 0; i < k; i++) {
split = br.readLine().split(" ");
for(int j = 0; j < n; j++) {
arr[i][j] = Integer.parseInt(split[j]);
}
}
dfs(1, 1);//组合型枚举找出所有的对数
int ans = 0;
for(int t = 0; t < count; t++) {
int num1 = 0;
int num2 = 0;
for(int i = 0; i < k; i++) {
int a = findIndex(couple[t][0], i);//第一头奶牛的位置
int b = findIndex(couple[t][1], i);//第二头奶牛的位置
if(a > b) {
num1++;
}else {
num2++;
}
}
if(num1 == k || num2 == k)ans++;//存在均符合条件的大小
}
System.out.println(ans);
}
public static int findIndex(int m, int row) {
for(int i = 0; i < arr[0].length; i++) {
if(arr[row][i] == m) {
return i;
}
}
return -1;
}
public static void dfs(int u, int start) {
if(u > 2) {
couple[count][0] = state[1];
couple[count][1] = state[2];
count++;
return;
}
for(int i = start; i <= n; i++) {
state[u] = i;
dfs(u + 1, i + 1);
state[u] = 0;
}
}
}
Java代码二:(数组模拟每头奶牛的排位)
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] split = br.readLine().split(" ");
int k = Integer.parseInt(split[0]);
int n = Integer.parseInt(split[1]);
int [][]arr = new int[k + 1][n + 1];
int [][]loc = new int[k + 1][n + 1];
for(int i = 1; i <= k; i++) {//题目给出的数组
split = br.readLine().split(" ");
for(int j = 0; j < n; j++) {
arr[i][j + 1] = Integer.parseInt(split[j]);
}
}
for(int i = 1; i <= k; i++) {//将给出的数组转化成“排位数组”
for(int j = 1; j <= n; j++) {
loc[i][arr[i][j]] = j;
}
}
int ans = 0;
for(int i = 1; i <= n; i++) {
for(int j =1; j <= n; j++) {
boolean flag = true;
for(int r = 1; r <= k; r++) {
if(loc[r][i] >= loc[r][j]) {//将非严格小于的情况过滤
flag = false;
}
}
if(flag)ans++;
}
}
System.out.println(ans);
}
}