GCJ 2009 Round2 Problem A. Crazy Rows

Problem A. Crazy Rows
This contest is open for practice. You can try every problem as many times as you like, though we won't keep track of which problems you solve. Read the Quick-Start Guide to get started.
Small input
6 points
Solve A-small
Large input
10 points

Solve A-large


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

题意:给定一个由0和1组成的矩阵。 只允许交换相邻的两行(第i行和第i + 1行), 把矩阵化为一个下三角矩阵(主对角线上方的元素都是0),, 最少的交换次数是多少? (注意, 假设我们给定的矩阵总能化为下三角矩阵)。 具体参考原题目。

分析: 每行的0和1的位置并不重要, 只要知道每行的最后一个1的位置就足够了。 如果将这些位置预先计算好, 那么就能降低行交换的复杂度了。  当有多个行满足某行的要求的时候, 选择距离这行最近的行交换代价最小。 可以先换好第1行, 然后第2行, 一次进行下去。

#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 45;

int t, n;
char m[maxn][maxn];    //矩阵
int a[maxn];     //a[i]表示第i行最后出现的1的位置
int main()
{
    scanf("%d", &t);
    for (int cas = 1; cas <= t; cas++){
        scanf("%d", &n);
        for (int i = 0; i < n; i++){
            scanf("%s", m[i]);
        }
        int res = 0;
        for (int i = 0; i < n; i++){
            a[i] = -1;
            for (int j = 0; j < n; j++){
                if (m[i][j] == '1')
                    a[i] = j;
            }
        }
        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("Case #%d: %d\n", cas, res);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值