A - Crazy Rows SPOJ - HAROWS

滴答滴答---题目链接 

Crazy Rows

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 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
  • 2.解题思路
    最先想到的是尝试所有N!种方案,
  • 但是在Large中最大的N=40,肯定会超时。
    暂时先考虑哪一行应该放在第一行。这一行应具有10000……或者00000……的形式。
  • 可以交换到第一行的当然也可以交换到第二行。
  • 当有多个条件满足时,选择离第一行最近的行对应的最终所需步数最小。
  • 确定第一行之后,剩余的行类似可以解决。
    每行的0和1的位置不重要,只要知道每行最后一个1的位置即可。
    如果预先处理好这些位置,就可以降低时间复杂度。
  • 时间复杂度为O(N^2)。
#include <algorithm>
#include<string.h>
#include<stdio.h>
#include <iostream>
using namespace std;
const int maxn=101;
int N;
int M[maxn][maxn];//矩阵

int a[maxn];//a[i]表示第i行最后出现1的位置

void solve()
{
    int res=0;
    for(int i=0; i<N; i++)
    {
        a[i]=-1;//如果不含1,就当作-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("%d\n",res);
}
int main()
{
    int t,kase=0;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&N);
        for(int i=0; i<N; i++)
        {
            char s[maxn];
            cin>>s;
            for(int j=0; j<N; j++)
            {
                M[i][j]=s[j]-'0';
            }
        }
        printf("Case #%d: ",++kase);
        solve();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/chen_zan_yu_/article/details/84546131