Problem
You are given an N x N matrix with 0 and 1 values. You can swap any two adjacent rows of the matrix.
Your goal is to have all the 1 values in the matrix below or on the main diagonal. That is, for each X where 1 ≤ X ≤ N, there must be no 1 values in row X that are to the right of column X.
Return the minimum number of row swaps you need to achieve the goal.
Input
The first line of input gives the number of cases, T. T test cases follow.
The first line of each test case has one integer, N. Each of the next N lines contains Ncharacters. Each character is either 0 or 1.
Output
For each test case, output
Case #X: Kwhere X is the test case number, starting from 1, and K is the minimum number of row swaps needed to have all the 1 values in the matrix below or on the main diagonal.
You are guaranteed that there is a solution for each test case.
Limits
1 ≤ T ≤ 60
Small dataset
1 ≤ N ≤ 8
Large dataset
1 ≤ N ≤ 40
Sample
这个题是贪心法吧,重点是对题目条件的挖掘:题目并没有要求行与行之间有一个顺序关系,只要是最后一位合规则就行了。因此题目所给数据可以直接变成以每行最后有一位所在位置为内容的一维数组,这样不论是判断还是交换都变简单了。而且题目的贪心精神也更显而易见了。
#include<stdio.h>
#define N 50
char mat[N][N];
int fin[N];
int main(void){
int t, tc;
scanf("%d", &t);
for(tc = 1; tc <= t; tc++){
int n, i, j;
scanf("%d", &n);
for(i = 0; i < n; i++){
char l[N];
scanf("%s", l);
for(j = n - 1; j >= 0; j--){
if(l[j] == '1'){
break;
}
}
fin[i] = j;
}
int ans = 0;
for(i = 0; i < n; i++){
for(j = i; j < n; j++){
if(fin[j] <= i){
break;
}
}
ans += j - i;
int t = fin[j];
int k = j;
for(k = j; k > i; k--){
fin[k] = fin[k - 1];
}
fin[i] = t;
}
printf("Case #%d: %d\n", tc, ans);
}
return 0;
}