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: K
where 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
Input
3
2
10
11
3
001
100
010
4
1110
1100
1100
1000
Output
Case #1: 0
Case #2: 2
Case #3: 4
#include<bits/stdc++.h>
using namespace std;
#define MAX_N 50
int m[MAX_N][MAX_N];
int a[MAX_N],n;
void solve(){
int res=0;
for(int i=0;i<n;i++){
a[i]=-1;//如果第i行不含 1
for(int j=0;j<n;j++){
if(m[i][j]==1)
a[i]=j;//得到每行最後一個 1 的位置
}
}
for(int i=0;i<n;i++){
int pos=-1;//要移到第i行的行
for(int j=i;j<n;j++){
if(a[j]<=i){
pos=j;
break;
}
}
//完成轉換
for(int j=pos;j>i;j--){
swap(a[j],a[j-1]);
res++;
}
}
printf("%d\n",res);
// for(int i=0;i<n;i++){//輸出查看
// for(int j=0;j<n;j++){
// printf("%d ",m[i][j]);
// }
// printf("\n");
// }
}
int main(){
while(scanf("%d",&n)!=EOF){
memset(m,0,sizeof(m));
memset(a,0,sizeof(a));
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",&m[i][j]);
}
}
solve();
printf("\n");
}
return 0;
}
題解:如果採用嘗試所有 N! 的種交換方案,當 N 大於40的時候時間複雜度就特別大,所以不可行,本題從第一行開始一行一行的尋找每行的最後一個 1 的位置,然後交換直到最後一行。