Crazy Rows (贪心)

Crazy Rows

You are given an N x N matrix with 0 and 1 values. You can swap any two adjacentrows 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, TT test cases follow.
The first line of each test case has one integer, N. Each of the next N lines contains N characters. 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

1 ≤ N ≤ 8

Input
 
Output 
 
3
2
10
11
3
001
100
010
4
1110
1100
1100
1000
Case #1: 0
Case #2: 2

Case #3: 4


贪心算法:一行一行走,首先从第一行从上往下找到第一个符合一行的交换下,然后再依次以这种方法处理下面几行

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;

const int maxn=50;

char m[maxn][maxn];
int a[maxn];

int main()
{
	int t,casen=0;
	scanf("%d",&t);
	while(t--){
		memset(a,0,sizeof(a));//这里的处理很关键,因为多组输入,a会残留上次的结果 
		int n;
		scanf("%d",&n);
		for(int i=1;i<=n;i++){
			scanf("%s",m[i]+1);
		}
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				if(m[i][j]=='1'){
					a[i]=j;
				}
			}
		}
	/*	for(int i=1;i<=n;i++){
			cout<<a[i]<<" ";
		}
		cout<<endl;*/
		int res=0;
		for(int i=1;i<=n;i++){
			int pos=-1;
			for(int j=i;j<=n;j++){
				if(a[j]<=i){//本题最核心的东西,找到即跳出 
					pos=j;
					break;
				}
			}
			for(int k=pos;k>i;k--){
				res++;
				swap(a[k],a[k-1]);
			}
		}
		printf("Case #%d: %d\n",++casen,res);
	}
	return 0;
}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页