王道机试 第二章 暴力求解
2.2 模拟
3、其他模拟
例题2.9 剩下的树(清华大学复试上机题)
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 10005 ;
bool tree[ maxn] ;
int main ( )
{
int L, m, a, b;
cin >> L >> m;
fill ( tree, tree + maxn, 1 ) ;
while ( m-- ) {
cin >> a >> b;
for ( int i = a; i <= b; i++ ) {
tree[ i] = false ;
}
}
int cnt = 0 ;
for ( int i = 0 ; i <= L; i++ ) {
if ( tree[ i] ) cnt++ ;
}
cout << cnt << endl;
return 0 ;
}
例题2.10 手机键盘
解题关键 1、要知道九宫格输入法的键盘布局 2、判断两个字母是否在同一个按键上的方法:若两个字母的位置之差等于时间之差,则它们在同一个按键上。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int times[ ] = {
1 , 2 , 3 ,
1 , 2 , 3 ,
1 , 2 , 3 ,
1 , 2 , 3 ,
1 , 2 , 3 ,
1 , 2 , 3 , 4 ,
1 , 2 , 3 ,
1 , 2 , 3 , 4
} ;
int main ( )
{
string s;
while ( cin >> s) {
int ans = 0 ;
for ( int i = 0 ; i < s. size ( ) ; i++ ) {
ans + = times[ s[ i] - 'a' ] ;
if ( i != 0 && s[ i] - s[ i - 1 ] == times[ s[ i] - 'a' ] - times[ s[ i - 1 ] - 'a' ] ) {
ans + = 2 ;
}
}
cout << ans << endl;
}
return 0 ;
}
例题2.11 XXX定律(浙江大学复试上机题)
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main ( )
{
int n;
while ( cin >> n && n) {
int cnt = 0 ;
while ( n != 1 ) {
if ( n % 2 == 0 ) { n / = 2 ; cnt++ ; }
else { n = 3 * n + 1 ; n / = 2 ; cnt++ ; }
}
cout << cnt << endl;
}
return 0 ;
}
习题2.9 Grading(浙江大学复试上机题)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int maxx ( int a, int b, int c) {
return ( max ( max ( a, b) , max ( a, c) ) ) ;
}
void solve ( int P, int T, int G1, int G2, int G3, int GJ)
{
float ans = 0.0 ;
if ( abs ( G1 - G2) <= T) ans = ( G1 + G2) / 2.0 ;
else {
if ( ( abs ( G1 - G3) <= T && abs ( G2 - G3) > T) || ( abs ( G1 - G3) > T && abs ( G2 - G3) <= T) ) {
if ( abs ( G1 - G3) < abs ( G1 - G2) ) ans = ( G1 + G3) / 2.0 ;
else ans = ( G2 + G3) / 2.0 ;
}
else if ( abs ( G1 - G3) <= T && abs ( G2 - G3) <= T) ans = maxx ( G1, G2, G3) ;
else ans = GJ;
}
printf ( "%.1f\n" , ans) ;
return ;
}
int main ( )
{
int P, T, G1, G2, G3, GJ;
while ( cin >> P >> T >> G1 >> G2 >> G3 >> GJ) {
solve ( P, T, G1, G2, G3, GJ) ;
}
return 0 ;
}