UVA OJ AOAPC I: Beginning Algorithm Contests (Rujia Liu) :: Volume 0. Getting Started
前言:编译器使用gcc/g++。题目均较为基础,涉及输入输出等
技巧:数组清零方法:memset。void *memset(void *s, int ch, size_t n); 包含在string.h头文件。memset是对每个字节赋值,因此对于char可赋予对应值,对于int只可赋值全0或全1. ex: int a[max]; memset(a,0,sizeof(a));
10055 Hashmat the brave warrior
题:读入两个数,求差的绝对值 (整数小于2的32次)
解:
1)由于int 只能表示到2的31次,故用long long;
2)c/c++中,abs(n)表示取int的绝对值,fabs(n)取double的绝对值。故对于long long型,自己编写abs (n)方法,用宏实现
#define abs(n) ((n)>=0?(n):(-n))
3)long long的输出,用"%lld"
4)scanf("...") 返回值如等于EOF,表示读到末尾。可如下用 while(scanf(...) !=EOF) {...}
458 The Decoder
题:读入字符串,对每个字符进行“编码”,ASCII码值-7
解:
#include<stdio.h>
#define MAX 1000
int main(){
char line[MAX];
int i;
while(gets(line)){
for(i=0;line[i]!='\0';i++)
line[i]-=7;
printf("%s\n",line);
}
return 0;
}
494 - Kindergarten Counting Game
题:单词统计。一个单词为连续的字符(大写或小写)。输出每行单词个数。
解:
1) 使用getchar()读入每个字符。使用flag标记当前字符是否在单词中。
若当前字符不为字母,而前一个在单词中,则单词结束。
#include <stdio.h>
#include <ctype.h>
#define IN 1
#define OUT 0
int main(){
char c;
int state = OUT,n=0;
while((c=getchar())!=EOF){
if(c!='\n'){
if(isalpha(c)){
state = IN;
}else{
if(state==IN)
n++;
state = OUT;
}
}else{
printf("%d\n",n);
n = 0;
}
}
return 0;
}
694 The Collatz Sequence
题:输入两个数,第一个为A,第二个为限制大小。如果A通过以下步骤,超过了限制大小,则停止。输出步数。
Step 1:
解:
#include <stdio.h>
int main(){
long long A,limit;
int cn=0,tn=0;
while(scanf("%lld %lld",&A,&limit)&&A>=0&&limit>=0){
printf("Case %d: A = %lld, limit = %lld, number of terms = ",++cn,A,limit);
tn = 0;
while(A>1&&A<=limit){
if(A%2==1){
A = A * 3 + 1;
}else{
A /= 2;
}
tn++;
}
if(A==1) tn++;
printf("%d\n",tn);
}
return 0;
}