Challenges Programming Contest: Crazy Rows

Subject to the effect

Here Insert Picture Description
Here Insert Picture Description

Problem-solving ideas

  • Greedy strategy:
    • (1) should first determine the line to the first line, the selected strategy is to be able to move into the first row nearest the line first line to move.
    • (2) is then determined by the same strategy the second line, third line ...
  • Correctness proof:
    • Use greedy exchange guidelines, the recent move to the line that the current line is determined, at least not to the number of steps than the other lines move the currently determined.
  • skill:
    • Per line with a number of records that the current position of the last 1. For example, matrix

      111
      110
      100

      It can be represented as 2,1,0

    • Currently determined first irow of the first matrix prior k k rows, if it satisfies the k > = i And a [ k ] < = i k>=i 且 a[k] <= i , it is possible, from the i-th position from left to right scan, the first scan line to meet, it is to simulate the exchange on the first i i row, and recording the number of exchanges.

Code

#include<iostream>
using namespace std;
const int MAXN = 40+2;

int a[MAXN];
int main()
{
    int N;
    string line;
    while(cin >> N)
    {
        for(int i=0; i<N; i++)
        {
            cin >> line;
            a[i] = 0;
            for(int j=line.length()-1; j>=0; j--)
            {
                if(line[j] == '1')
                {
                    a[i] = j;
                    break;
                }
            }
        }

        int ans = 0;
        for(int i=0; i<N; i++)
        {
            for(int j=i; j<N; j++)
            {
                if(a[j] <= i)
                {
                    for(int k=j-1; k>=i; k--)
                    {
                        swap(a[k], a[k+1]);
                        ans++;
                    }
                    break;
                }
            }
        }
        cout << ans << endl;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/Wangpeiyi9979/article/details/93758110