UVA 算法竞赛入门 GettingStarted 解题报告 (上)

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:
Choose an arbitrary positive integer A as the first item in the sequence.
Step 2:
If A = 1 then stop.
Step 3:
If A is even, then replace A by A / 2 and go to step 2.
Step 4:
If A is odd, then replace A by 3 * A + 1 and go to step 2.

解:

#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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值