Article Directory
Subject to the effect
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
100It can be represented as 2,1,0
-
Currently determined first
i
row of the first matrix prior rows, if it satisfies the , 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 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;
}