#include "stdio.h" #include "string.h" #include "windows.h" int partition( int * a, int * pos, int p, int r ) { int x = a[p]; int px = p; int i = p, j = r + 1; int temp; while ( 1 ) { while ( a[++i] > x && i < r ); while ( a[--j] < x ); if ( i >= j ) break; temp = a[i]; a[i] = a[j]; a[j] = temp; temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; } a[p] = a[j]; a[j] = x; pos[p] = pos[j]; pos[j] = px; return j; } void MySort( int * a, int * pos, int p, int r ) { int q; if ( p < r ) { q = partition( a, pos, p, r ); MySort( a, pos, p, q - 1 ); MySort( a, pos, q + 1, r ); } } long fillmark( long p, int pos ,int total ) { int i; long temp = p; long mul = 1; int modt; for ( i = 0; i < total; i++ ) { modt = temp % 2; if ( i > 0 ) mul *= 2; if (( i + pos ) == total - 1 ) { p = p + mul; break; } temp /= 2; } return p; } int filledmark( long p, int pos, int total ) { int i; long temp = p; int modt; for ( i = 0; i < total; i++ ) { modt = temp % 2; if (( i + pos ) == total - 1 && modt ) return 0; temp /= 2; } return 1; } int myabs( int a ) { if ( a >= 0 ) return a; else return -a; } int main() { int T, i, j, k, l; char a[1001]; char b[1001]; int lena, lenb; int res[101] = { 0 }; int map[1001] = { 0 }; int temp[1001] = { 0 }; int origin[1001] = { 0 }; long mark[1001] = { 0 }; int pos[1001] = { 0 }; int max, sum; int total; scanf( "%d", &T ); for ( k = 0; k < T; k++ ) { sum = 0; scanf( "%s", a ); scanf( "%s", b ); lena = strlen( a ); lenb = strlen( b ); total = lena - 1; for ( j = 0; j < lena - 1; j++ ) { origin[j] = myabs( a[j] - a[j + 1]); sum += origin[j]; map[j] = myabs( a[j] - b[0] ) + myabs( a[j + 1] - b[0] ) - origin[j]; mark[j] = fillmark( mark[j], j, total ); pos[j] = j; } for ( i = 1; i < lenb; i++ ) { for ( j = 0; j < lena - 1; j++ ) temp[j] = myabs( a[j] - b[i] ) + myabs( a[j + 1] - b[i] ) - origin[j]; MySort( temp, pos, 0, lena - 2 ); for ( l = 0; l < lena - 1; l++ ) { max = 0; for ( j = 0; j < lena - 1; j++ ) if (filledmark( mark[l], pos[j], total )) break; mark[l] = fillmark( mark[l], pos[j], total ); map[l] += temp[j]; } } max = 0; for ( j = 0; j < lena - 1; j++ ) if ( map[j] > max ) max = map[j]; res[k] = max + sum; } for ( k = 0; k < T; k++ ) printf( "%d/n", res[k] ); system( "pause" ); return 0; }
校赛填充数字串的代码。