[Code Jam] Crazy Rows

本文介绍了一种算法,该算法旨在解决一个特定问题:给定一个N×N的矩阵,通过最少次数的行交换操作,使得所有1元素位于或低于主对角线的位置。文章提供了详细的输入输出说明,并附带了一个C语言实现的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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, TT 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 
 

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

这个题是贪心法吧,重点是对题目条件的挖掘:

题目并没有要求行与行之间有一个顺序关系,只要是最后一位合规则就行了。因此题目所给数据可以直接变成以每行最后有一位所在位置为内容的一维数组,这样不论是判断还是交换都变简单了。而且题目的贪心精神也更显而易见了。

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值