Pagini recente » Cod sursa (job #1454228) | Cod sursa (job #2849029) | Cod sursa (job #2415500) | primuld | Cod sursa (job #567048)
Cod sursa(job #567048)
# include <cstdio>
using namespace std;
int n, m, i, j, x1, x2, y1, y2, nr, sol, k;
int a[ 301 ][ 301 ], v[45001][5], pl1[301], pl2[301], pc1[301], pc2[301];
int main () {
freopen ( "mahjong.in", "rt", stdin );
freopen ( "mahjong.out", "wt", stdout );
scanf ( "%d%d", &n, &m );
for ( i = 1; i <= n; ++i ) {
for ( j = 1; j <= m; ++j ) {
scanf ( "%d", &a[ i ][ j ] );
x1 = a[i][j];
v[x1][++v[x1][0]] = i;
v[x1][++v[x1][0]] = j;
}
}
do {
nr = 0;
for ( i = 1; i <= n; ) {
k = a[ i ][ 1 + pl1[ i ] ];
if ( k ) {
if ( i == v[k][1] && ( 1 + pl1[i] ) == v[k][2] ) {
x1 = i; y1 = 1 + pl1[i];
x2 = v[k][3]; y2 = v[k][4];
}
else {
x1 = i; y1 = 1 + pl1[i];
x2 = v[k][1]; y2 = v[k][2];
}
if ( y2 == 1 + pl1[x2] ) {
nr = 1; ++sol;
a[x1][y1] = a[x2][y2] = 0;
while ( !a[x1][y1] && y1 <= m ) {++pl1[x1]; ++y1;}
while ( !a[x2][y2] && y2 <= m ) {++pl1[x2]; ++y2;}
}
else ++i;
}
else {
while ( !a[ i ][ 1 + pl1[ i ] ] && pl1[i] < m ) ++pl1[i];
++i;
}
}
for ( j = 1; j <= m; ) {
k = a[1 + pc1[ j ]][ j ];
if ( k ) {
if ( ( 1 + pc1[j] ) == v[k][1] && j == v[k][2] ) {
x1 = 1 + pc1[j]; y1 = j;
x2 = v[k][3]; y2 = v[k][4];
}
else {
x1 = 1 + pc1[j]; y1 = j;
x2 = v[k][1]; y2 = v[k][2];
}
if ( x2 == 1 + pc1[y2] ) {
nr = 1; ++sol;
a[x1][y1] = a[x2][y2] = 0;
while ( !a[x1][y1] && x1 <= n) {++pc1[y1]; ++x1;}
while ( !a[x2][y2] && x2 <= n) {++pc1[y2]; ++x2;}
}
else ++j;
}
else {
while ( !a[ 1 + pc1[ j ]][ j ] && pc1[j] < n ) ++pc1[j];
++j;
}
}
for ( i = 1; i <= n; ) {
k = a[i][m - pl2[i] ];
if ( k ) {
if ( i == v[k][1] && ( m - pl2[i] ) == v[k][2] ) {
x1 = i; y1 = m - pl2[i];
x2 = v[k][3]; y2 = v[k][4];
}
else {
x1 = i; y1 = m - pl2[i];
x2 = v[k][1]; y2 = v[k][2];
}
if ( y2 == m - pl2[x2] ) {
nr = 1; ++sol;
a[x1][y1] = a[x2][y2] = 0;
while ( !a[x1][y1] && y1 > 0 ) {++pl2[x1]; --y1;}
while ( !a[x2][y2] && y2 > 0 ) {++pl2[x2]; --y2;}
}
else ++i;
}
else {
while ( !a[ i ][ m - pl2[i]] && pl2[i] < m ) ++ pl2[i];
++i;
}
}
for ( j = 1; j <= m; ) {
k = a[ n - pc2[j] ][ j ];
if ( k ) {
if ( ( n - pc2[j] ) == v[k][1] && j == v[k][2] ) {
x1 = n - pc2[j]; y1 = j;
x2 = v[k][3]; y2 = v[k][4];
}
else {
x1 = n - pc2[j]; y1 = j;
x2 = v[k][1]; y2 = v[k][2];
}
if ( x2 == n - pc2[y2] ) {
nr = 1; ++sol;
a[x1][y1] = a[x2][y2] = 0;
while ( !a[x1][y1] && x1 > 0 ) {++pc2[y1]; --x1;}
while ( !a[x2][y2] && x2 > 0 ) {++pc2[y2]; --x2;}
}
else ++j;
}
else {
while ( !a[ n - pc2[j] ][ j ] && pc2[j] < n ) ++pc2[j];
++j;
}
}
} while ( nr );
printf ( "%d\n", sol );
return 0;
}