四.完善程序 (前4空,每空2.5分,后6空,每空3分,共28分)
1.(求字符串的逆序)
下面的程序的功能是输入若干行字符串,每输入一行,就按逆序输出该行,最后键入-1终止程序。
请将程序补充完整。
/*
NOIP 2007 普及组初赛试题完善程序01:
(求字符的逆序)下面的程序的功能是输入若干行字符串,
每输入一行,就按逆序输出该行,最后键入-1终止程序。
请将程序补充完整。
*/
#include <iostream.h>
#include <string.h>
int maxline = 200, kz;
int reverse( char s[] )
{
int i, j, t;
for ( i = 0, j = strlen( s ) - 1; i < j; 【①】 , 【②】 )
{
t = s[i]; s[i] = s[j]; s[j] = t;
}
return(0);
}
void main()
{
char line[100];
cout << "continue? -1 for end." <<endl;
cin>>kz;
while(【③】)
{
cin >> line;
【④】;
cout << line << endl;
cout << "continue ? -1 for end." << endl;
cin >> kz;
}
}
/*
1.正确答案: i++ / i=i+1 / i+=1
2.正确答案: j-- / j=j-1 / j-=1
3.正确答案: kz!=-1
4.正确答案: reverse(line)
*/
- (棋盘覆盖问题)
在一个2^k ×2^k 个方格组成的棋盘中恰有一个方格与其他方格不同(图中标记为-1的方格),称之为特殊方格。现用L型(占3个小格)纸片覆盖棋盘上除特殊方格的所有部分,各纸片不得重叠,于是,用到的纸片数恰好是(4^k -1)/3。在下表给出的一个覆盖方案中,k=2,相同的3个数字构成一个纸片。
下面给出的程序是用分治法设计的,将棋盘一分为四,依次处理左上角、右上角、左下角、右下角,递归进行。请将程序补充完整。
2 | 2 | 3 | 3 |
2 | -1 | 1 | 3 |
4 | 1 | 1 | 5 |
4 | 4 | 5 | 5 |
#include <iostream.h>
#include <iomanip.h>
int board[65][65], tile; /* tile为纸片编号 */
void chessboard( int tr, int tc, int dr, int dc, int size )
/* dr,dc依次为特殊方格的行、列号 */
{
int t, s;
if ( size == 1 )
⑤ ;
t = tile++;
s = size / 2;
if ( ⑥ )
chessboard( tr, tc, dr, dc, s );
else{
board[tr + s - l][tc + s - l] = t;
[⑦];
}
if ( dr < tr + s && dc >= tc + s )
chessboard( tr, tc + s, dr, dc, s );
else{
board[tr + s - l][tc + s] = t;
⑧;
}
if ( dr >= tr + s && dc < tc + s )
chessboard( tr + s, tc, dr, dc, s );
else{
board[tr + s][tc + s - l] = t;
[⑨];
}
if ( dr >= tr + s && dc >= tc + s )
chessboard( tr + s, tc + s, dr, dc, s );
else{ board[tr + s][tc + s] = t;
[⑩]; }
}
void prtl( int b[][65], int n )
{
int i, j;
for ( i = l; i <= n; i++ )
{
for ( j = l; j <= n; j++ )
cout << setw( 3 ) << b[i][j];
cout << endl;
}
}
void main()
{
int size, dr, dc;
cout << "input size(4/8/16/64):" << endl;
cin >> size;
cout << "input the position of special block(x,y):" << endl;
cin >> dr >> dc;
board[dr][dc] = -l;
tile++;
chessboard( 1, 1, dr, dc, size );
prtl( board, size );
}
/*
1.正确答案: return
2.正确答案: (dr<tr+s)&&(dc<tc+s)
3.正确答案: chessboard(tr,tc,tr+s-1,tc+s-1,s)
4.正确答案: chessboard(tr,tc+s,tr+s-1,tc+s,s)
5.正确答案: chessboard(tr+s,tc,tr+s,tc+s-1,s)
6.正确答案: chessboard(tr+s,tc+s,tr+s,tc+s,s)
*/