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
Input |
Output |
3 |
Case #1: 0 |
思路很简单,我去记录每一行的最后一个1的位置a[i],然后该行如果移动,移动至第i行最优。
#include <cstdio> #include <cmath> #include <algorithm> #include <iostream> #include <cstring> #include <map> #include <string> #include <stack> #include <cctype> #include <vector> #include <queue> #include <set> #include <utility> using namespace std; #define Online_Judge #define outstars cout << "***********************" << endl; #define clr(a,b) memset(a,b,sizeof(a)) #define lson l , mid , rt << 1 #define rson mid + 1 , r , rt << 1 | 1 //#define mid ((l + r) >> 1) #define mk make_pair #define FOR(i , x , n) for(int i = (x) ; i < (n) ; i++) #define FORR(i , x , n) for(int i = (x) ; i <= (n) ; i++) #define REP(i , x , n) for(int i = (x) ; i > (n) ; i--) #define REPP(i ,x , n) for(int i = (x) ; i >= (n) ; i--) #define bug(s) cout<<"#s = "<< s << endl; const int MAXN = 100 ; const long long LLMAX = 0x7fffffffffffffffLL; const long long LLMIN = 0x8000000000000000LL; const int INF = 0x7fffffff; const int IMIN = 0x80000000; #define eps 1e-8 #define mod 1000000007 typedef long long LL; const double PI = acos(-1.0); typedef double D; typedef pair<int , int> pi; ///#pragma comment(linker, "/STACK:102400000,102400000") char G[MAXN][MAXN]; int a[MAXN]; int ans , n; void solve() { FOR(i , 0 , n) { a[i] = -1; FOR(j , 0 , n)if(G[i][j] == '1') { a[i] = j; } } ans = 0; FOR(i , 0 , n) { int pos = -1; FOR(j , i , n) { if(a[j] <= i) { pos = j; break; } } REP(j , pos , i) { swap(a[j] , a[j - 1]); ans++; } } // cout << ans << endl; } int main() { //ios::sync_with_stdio(false); #ifdef Online_Judge freopen("A-large-practice.in","r",stdin); freopen("A-large-practice.out","w",stdout); #endif // Online_Judge int t ; cin >> t; FORR(kase , 1 , t) { scanf("%d" , &n); FOR(i , 0 , n)scanf("%s" , G[i]); ans = 0; solve(); printf("Case #%d: %d\n" , kase , ans); } return 0; }