1. 程式人生 > >小白的刷題之路1--紫書第三章習題UVA-455,UVA-227,UVA-232,UVA-1368,UVA-202,UVA-10340,UVA-1587,UVA-1588,UVA-11809

小白的刷題之路1--紫書第三章習題UVA-455,UVA-227,UVA-232,UVA-1368,UVA-202,UVA-10340,UVA-1587,UVA-1588,UVA-11809

寫在前面

第一次寫博文,求大佬輕拍。。。我是真的小白,雖然是大四生,但幾乎算是非科班出身了,前三年讀的是北京一所211的機械,就學了個C。。。大三下準備保研,思前想後感覺對機械興趣真的不大,就想著轉cs,勉強保到一所中下985,趁著大四還算閒,就想著刷刷題希望漲漲水平。。。

 

1. Score   UVA - 1585

 題目連結: UVA-1585

題目描述:      

 There is an objective test result such as “OOXXOXXOOO”. An ‘O’ means a correct answer of a problem and an ‘X’ means a wrong answer. The score of each problem of this test is calculated by itself and its just previous consecutive ‘O’s only when the answer is correct. For example, the score of the 10th problem is 3 that is obtained by itself and its two previous consecutive ‘O’s. Therefore, the score of “OOXXOXXOOO” is 10 which is calculated by “1+2+0+0+1+0+0+1+2+3”. You are to write a program calculating the scores of test results.
Input
Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing a string composed by ‘O’ and ‘X’ and the length of the string is more than 0 and less than 80. There is no spaces between ‘O’ and ‘X’.
Output
Your program is to write to standard output. Print exactly one line for each test case. The line is to contain the score of the test case.
Sample Input
5

OOXXOXXOOO

OOXXOOXXOO

OXOXOXOXOXOXOX

OOOOOOOOOO

OOOOXOOOOXOOOOX
Sample Output
10

9

7

55

30

問題分析:直接模擬

//AC程式碼
#include<iostream>
using namespace std;
const int maxn=100;
int main()
{
	char p[maxn];
	int n,num,sum;
	cin>>n;
	while(n--){
		scanf("%s",p);
		num=0,sum=0;
		for(int i=0;p[i];++i)
			if(p[i]=='O') ++num,sum+=num;
			else if(p[i]=='X') num=0;
		cout<<sum<<endl;
	}
	return 0;
}

 

 

2.Molar mass      UVA - 1586

題目連結:UVA-1586

題目描述:

An organic compound is any member of a large class of chemical compounds whose molecules contain carbon. The molar mass of an organic compound is the mass of one mole of the organic compound. The molar mass of an organic compound can be computed from the standard atomic weights of the elements. When an organic compound is given as a molecular formula, Dr. CHON wants to find its molar mass. A molecular formula, such as C3H4O3, identifies each constituent element by its chemical symbol and indicates the number of atoms of each element found in each discrete molecule of that compound. If a molecule contains more than one atom of a particular element, this quantity is indicated using a subscript after the chemical symbol. In this problem, we assume that the molecular formula is represented by only four elements, ‘C’ (Carbon), ‘H’ (Hydrogen), ‘O’ (Oxygen), and ‘N’ (Nitrogen) without parentheses. The following table shows that the standard atomic weights for ‘C’, ‘H’, ‘O’, and ‘N’.
For example, the molar mass of a molecular formula C6H5OH is 94.108 g/mol which is computed by 6 × (12.01 g/mol) + 6 × (1.008 g/mol) + 1 × (16.00 g/mol). Given a molecular formula, write a program to compute the molar mass of the formula.

Input
Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case is given in a single line, which contains a molecular formula as a string. The chemical symbol is given by a capital letter and the length of the string is greater than 0 and less than 80. The quantity number n which is represented after the chemical symbol would be omitted when the number is 1 (2 ≤ n ≤ 99).
Output
Your program is to write to standard output. Print exactly one line for each test case. The line should contain the molar mass of the given molecular formula.
Sample Input
4

C

C6H5OH

NH2CH2COOH

C12H22O11

Sample Output
12.010

94.108

75.070

342.296

問題分析:取兩字母之間的數字

AC程式碼:

#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
const int maxn=80+9;
double num(char p)//取原子質量 
{
	if(p=='C') return 12.01;
	if(p=='H') return 1.008;
	if(p=='O') return 16;
	if(p=='N') return 14.01;
}
int main()
{
	int n;
	cin>>n;
	while(n--){
		char pq[maxn],tmp[maxn];
		scanf("%s",pq);
		int pos=0;
		double sum=0,weight;
		while(pq[pos]){
			if(pq[pos]>='A'&&pq[pos]<='Z'){
				weight=num(pq[pos++]);
				int jk=1,cnt=0;
				while(pq[pos]>='0'&&pq[pos]<='9')
					tmp[cnt++]=pq[pos++];
				tmp[cnt]='\0';
				if(cnt>0) jk=atoi(tmp);//避免對空字串操作 
				sum+=jk*weight;
			}
		}
		printf("%.3lf\n",sum);
	}
	return 0;
}

3.Digit Counting  UVA - 1225

題目連結:UVA-1225

題目描述:

Trung is bored with his mathematics homeworks. He takes a piece of chalk and starts writing a sequence of consecutive integers starting with 1 to N (1 < N < 10000). After that, he counts the number of times each digit (0 to 9) appears in the sequence. For example, with N = 13, the sequence is:
12345678910111213
In this sequence, 0 appears once, 1 appears 6 times, 2 appears 2 times, 3 appears 3 times, and each digit from 4 to 9 appears once. After playing for a while, Trung gets bored again. He now wants to write a program to do this for him. Your task is to help him with writing this program.
Input
The input file consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 20. The following lines describe the data sets. For each test case, there is one single line containing the number N.
Output
For each test case, write sequentially in one line the number of digit 0,1,...9 separated by a space.
Sample Input
2

3

13

Sample Output
0 1 1 1 0 0 0 0 0 0

1 6 2 2 1 1 1 1 1 1

問題分析:查表,從n到n+1時先將n時的情況拷貝,再處理數n+1

AC程式碼:

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int pq[10009][10];
int main()
{
	memset(pq,0,sizeof(pq));
	for(int i=1;i<=10000;++i){
		for(int j=0;j<10;++j) pq[i][j]=pq[i-1][j];//處理當前情況之前先將上一次的拷貝 
		int yu=i;
		while(yu>0){ //處理當前數i 
			++pq[i][yu%10];
			yu/=10;
		}
	}
	int num,n;
	cin>>num;
	while(num--){
		cin>>n;
		for(int i=0;i<10;++i)
			if(!i) cout<<pq[n][i];
			else cout<<" "<<pq[n][i];
		cout<<endl;
	}
	return 0;
} 

 

4.Periodic Strings   UVA - 455

問題連結:UVA-455

問題描述:

A character string is said to have period k if it can be formed by concatenating one or more repetitions of another string of length k. For example, the string ”abcabcabcabc” has period 3, since it is formed by 4 repetitions of the string ”abc”. It also has periods 6 (two repetitions of ”abcabc”) and 12 (one repetition of ”abcabcabcabc”). Write a program to read a character string and determine its smallest period. 

Input

The first line oif the input file will contain a single integer N indicating how many test case that your program will test followed by a blank line. Each test case will contain a single character string of up to 80 non-blank characters. Two consecutive input will separated by a blank line.

Output

An integer denoting the smallest period of the input string for each input. Two consecutive output are separated by a blank line.

Sample Input

1
HoHoHo

Sample Output

問題分析:直接模擬

AC程式碼:

#include<iostream>
#include<cstring>
using namespace std;
const int maxn=90;
int main()
{
	char pq[maxn];
	int n,num;
	cin>>n;
	while(n--){
		scanf("%s",pq);
		num=strlen(pq);
		char tmp[maxn];
		int period=num;
		for(int i=1;i<=num/2;++i){
			if(num%i) continue;//週期如果不能整除則跳過 
			for(int j=0;j<i;++j) tmp[j]=pq[j];
			int flag=1;
			for(int j=0;j<num;++j)
				if(pq[j]!=tmp[j%i]){flag=0;break;}
			if(flag){period=i;break;}
		}
		cout<<period<<endl;
		if(n) cout<<endl;
	}
	return 0;
}

5.Puzzle  UVA - 227

問題連結:UVA-227

問題描述:
A children’s puzzle that was popular 30 years ago consisted of a 5×5 frame which contained 24 small squares of equal size. A unique letter of the alphabet was printed on each small square. Since there were only 24 squares within the frame, the frame also contained an empty position which was the same size as a small square. A square could be moved into that empty position if it were immediately to the right, to the left, above, or below the empty position. The object of the puzzle was to slide squares into the empty position so that the frame displayed the letters in alphabetical order.
Write a program to display resulting frames given their initial configurations and sequences of moves.
Input
Input for your program consists of several puzzles. Each is described by its initial configuration and the sequence of moves on the puzzle. The first 5 lines of each puzzle description are the starting configuration. Subsequent lines give the sequence of moves.
The first line of the frame display corresponds to the top line of squares in the puzzle. The other lines follow in order. The empty position in a frame is indicated by a blank. Each display line contains exactly 5 characters, beginning with the character on the leftmost square (or a blank if the leftmost square is actually the empty frame position). The display lines will correspond to a legitimate puzzle.
The sequence of moves is represented by a sequence of As, Bs, Rs, and Ls to denote which square moves into the empty position. A denotes that the square above the empty position moves; B denotes that the square below the empty position moves; L denotes that the square to the left of the empty position moves; R denotes that the square to the right of the empty position moves. It is possible that there is an illegal move, even when it is represented by one of the 4 move characters. If an illegal move occurs, the puzzle is considered to have no final configuration. This sequence of moves may be spread over several lines, but it always ends in the digit 0. The end of data is denoted by the character Z.
Output
Output for each puzzle begins with an appropriately labeled number (Puzzle #1, Puzzle #2, etc.). If the puzzle has no final configuration, then a message to that effect should follow. Otherwise that final configuration should be displayed.
Format each line for a final configuration so that there is a single blank character between two adjacent letters. Treat the empty square the same as a letter. For example, if the blank is an interior position, then it will appear as a sequence of 3 blanks — one to separate it from the square to the left, one for the empty position itself, and one to separate it from the square to the right.
Separate output from different puzzle records by one blank line.
Note: The first record of the sample input corresponds to the puzzle illustrated above.

 

問題分析:直接模擬,字元的輸入注意應去除一些回車字元以免對讀入資料造成干擾

AC程式碼:

#include<iostream>
using namespace std;
int main()
{
	char pq[5][5],p,op[10000];
	int posx,posy,cnt=1;
	while(1){
		if(cnt>1) getchar();//這裡要吃掉一個回車 
		p=getchar();
		if(p=='Z') break;
		for(int i=0;i<5;++i){
			for(int j=0;j<5;++j){
				if(!i&&!j) pq[i][j]=p;
				else scanf("%c",&pq[i][j]);
				if(pq[i][j]==' ') posx=i,posy=j;
			}
			getchar();//每行結束後吃掉一個回車 
		}
		int pos=0; 
		while(1){
			p=getchar();
			if(p=='0'){op[pos++]=p;op[pos]='\0';break;}
			else if(!(p>='A'&&p<='Z')) continue;//跳過干擾字元 
			op[pos++]=p;
		}
		int flag=1,tmpx,tmpy;
		for(int i=0;op[i]!='0';++i){
			if(op[i]=='A') tmpx=posx-1,tmpy=posy;
			else if(op[i]=='B') tmpx=posx+1,tmpy=posy;
			else if(op[i]=='L') tmpx=posx,tmpy=posy-1;
			else if(op[i]=='R') tmpx=posx,tmpy=posy+1;
			if(tmpx<0||tmpx==5||tmpy<0||tmpy==5) {flag=0;break;}
			pq[posx][posy]=pq[tmpx][tmpy];pq[tmpx][tmpy]=' ';
			posx=tmpx;posy=tmpy;
		}
		if(cnt>1) cout<<endl;
		printf("Puzzle #%d:\n",cnt++);
		if(!flag) printf("This puzzle has no final configuration.\n");
		else{
			for(int i=0;i<5;++i){
				for(int j=0;j<5;++j)
					if(!j) printf("%c",pq[i][j]);
					else printf(" %c",pq[i][j]);
				cout<<endl;
			}
		}
	}
	return 0;
}

6.Crossword Answers  UVA - 232

問題連結:UVA-232

問題描述:

A crossword puzzle consists of a rectangular grid of black and white squares and two lists of definitions (or descriptions). One list of definitions is for “words” to be written left to right across white squares in the rows and the other list is for words to be written down white squares in the columns. (A word is a sequence of alphabetic characters.) To solve a crossword puzzle, one writes the words corresponding to the definitions on the white squares of the grid.
The definitions correspond to the rectangular grid by means of sequential integers on “eligible” white squares. White squares with black squares immediately to the left or above them are “eligible.” White squares with no squares either immediately to the left or above are also “eligible.” No other squares are numbered. All of the squares on the first row are numbered. The numbering starts with 1 and continues consecutively across white squares of the first row, then across the eligible white squares of the second row, then across the eligible white squares of the third row and so on across all of the rest of the rows of the puzzle. The picture below illustrates a rectangular crossword puzzle grid with appropriate numbering. An “across” word for a definition is written on a sequence of white squares in a row starting on a numbered square that does not follow another white square in the same row. The sequence of white squares for that word goes across the row of the numbered square, ending immediately before the next black square in the row or in the rightmost square of the row.
A “down” word for a definition is written on a sequence of white squares in a column starting on a numbered square that does not follow another white square in the same column. The sequence of white squares for that word goes down the column of the numbered square, ending immediately before the next black square in the column or in the bottom square of the column. Every white square in a correctly solved puzzle contains a letter.
You must write a program that takes several solved crossword puzzles as input and outputs the lists of across and down words which constitute the solutions.
Input

Each puzzle solution in the input starts with a line containing two integers r and c (1 ≤ r ≤ 10 and 1 ≤ c ≤ 10), where r (the first number) is the number of rows in the puzzle and c (the second number) is the number of columns. The r rows of input which follow each contain c characters (excluding the end-of-line) which describe the solution. Each of those c characters is an alphabetic character which is part of a word or the character ‘*’, which indicates a black square. The end of input is indicated by a line consisting of the single number ‘0’.
Output
Output for each puzzle consists of an identifier for the puzzle (puzzle #1:, puzzle #2:, etc.) and the list of across words followed by the list of down words. Words in each list must be output one-per-line in increasing order of the number of their corresponding definitions. The heading for the list of across words is ‘Across’. The heading for the list of down words is ‘Down’. In the case where the lists are empty (all squares in the grid are black), the ‘Across’ and ‘Down’ headings should still appear.
Separate output for successive input puzzles by a blank line.

問題分析:直接模擬

AC程式碼:
 

#include<iostream>
#include<cstring>
using namespace std;
const int maxn=15;
int main()
{
	int r,c,jk=1;
	char pq[maxn][maxn],st[maxn][maxn],pos[maxn][maxn];
	//st中0表示都不是,1表示是行起始,2表示是列起始,3表示二者都是 
	while(cin>>r){
		if(!r) break;
		cin>>c;
		if(jk>1) printf("\n");
		printf("puzzle #%d:\nAcross\n",jk++);
		for(int i=0;i<r;++i) scanf("%s",pq[i]);
		memset(st,0,sizeof(st));
		memset(pos,0,sizeof(pos));
		int cnt=1;
		for(int i=0;i<r;++i)
			for(int j=0;j<c;++j)
				if(pq[i][j]!='*'){
					if(!j||j>0&&pq[i][j-1]=='*'){
						st[i][j]=1,pos[i][j]=cnt++;
						char tmp[maxn];
						int num=0;
						for(int k=j;k<c&&pq[i][k]!='*';++k) tmp[num++]=pq[i][k];
						tmp[num]='\0';
						printf("%3d.%s\n",pos[i][j],tmp);//注意數字應占三個位,不足用空格補齊 
					}
					if(!i||i>0&&pq[i-1][j]=='*'){
						if(st[i][j]) st[i][j]=3;
						else st[i][j]=2;
						if(!pos[i][j]) pos[i][j]=cnt++;
					}
				}
		printf("Down\n");
		for(int i=0;i<r;++i)
			for(int j=0;j<c;++j)
				if(st[i][j]==2||st[i][j]==3){
					char tmp[maxn];
					int num=0;
					for(int k=i;k<r&&pq[k][j]!='*';++k) tmp[num++]=pq[k][j];
					tmp[num]='\0';
					printf("%3d.%s\n",pos[i][j],tmp);
				}
					
	}
	return 0;
} 

7.DNA Consensus StringUVA - 1368

問題連結:UVA-1368

問題描述:

DNA (Deoxyribonucleic Acid) is the molecule which contains the genetic instructions. It consists of four different nucleotides, namely Adenine, Thymine, Guanine, and Cytosine as shown in Figure 1. If we represent a nucleotide by its initial character, a DNA strand can be regarded as a long string (sequence of characters) consisting of the four characters A, T, G, and C. For example, assume we are given some part of a DNA strand which is composed of the following sequence of nucleotides:
“Thymine-Adenine-Adenine-Cytosine-Thymine-Guanine-CytosineCytosine-Guanine-Adenine-Thymine”
Then we can represent the above DNA strand with the string “TAACTGCCGAT.”
The biologist Prof. Ahn found that a gene X commonly exists in the DNA strands of five different kinds of animals, namely dogs, cats, horses, cows, and monkeys. He also discovered that the DNA sequences of the gene X from each animal were very alike. See Figure 2.
Prof. Ahn thought that humans might also have the gene X and decided to search for the DNA sequence of X in human DNA. However, before searching, he should define a representative DNA sequence of gene X because its sequences are not exactly the same in the DNA of the five animals. He decided to use the Hamming distance to define the representative sequence. The Hamming distance is the number of different characters at each position from two strings of equal length. For example, assume we are given the two strings “AGCAT” and “GGAAT.” The Hamming distance of these two strings is 2 because the 1st and the 3rd characters of the two strings are different. Using the Hamming distance, we can define a representative string for a set of multiple strings of equal length. Given a set of strings S = {s1,...,sm} of length n, the consensus error between a string y of length n and the set S is the sum of the Hamming distances between y and each si in S. If the consensus error between y and S is the minimum among all possible strings y of length n, y is called a consensus string of S. For example, given the three strings “AGCAT” “AGACT” and “GGAAT” the consensus string of the given strings is “AGAAT” because the sum of the Hamming distances between “AGAAT” and the three strings is 3 which is minimal. (In this case, the consensus string is unique, but in general, there can be more than one consensus string.) We use the consensus string as a representative of the DNA sequence. For the example of Figure 2 above, a consensus string of gene X is “GCAAATGGCTGTGCA” and the consensus error is 7.
Input
Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing two integers m and n which are separated by a single space. The integer m (4 ≤ m ≤ 50) represents the number of DNA sequences and n (4 ≤ n ≤ 1000) represents the length of the DNA sequences, respectively. In each of the next m lines, each DNA sequence is given.
Output
Your program is to write to standard output. Print the consensus string in the first line of each case and the consensus error in the second line of each case. If there exists more than one consensus string, print the lexicographically smallest consensus string.
 

問題分析:每個位置上應填的是m個序列中在該位置出現最多次的字母,相同時取字典序小的

AC程式碼:
 

#include<iostream>
#include<cstring>
using namespace std;
const int inf=1000000;
const int maxn=1009;
char pq[55][maxn],item[4]={'A','C','G','T'};//按字典序排列 
int main()
{
	int t,m,n,num[4];
	cin>>t;
	while(t--){
		cin>>m>>n;
		for(int i=0;i<m;++i) scanf("%s",pq[i]);
		char tmp[maxn];
		int sum=0;
		for(int i=0;i<n;++i){//對每個位置判斷 
			memset(num,0,sizeof(num));
			for(int j=0;j<m;++j)//統計各元素出現次數 
				for(int k=0;k<4;++k)
					if(pq[j][i]==item[k]){++num[k];break;}
			int pos=0,jk=num[0];//jk表示最大出現次數 
			for(int j=1;j<4;++j)
				if(num[j]>jk) pos=j,jk=num[j];
			tmp[i]=item[pos];
			for(int j=0;j<4;++j)
				if(j!=pos) sum+=num[j];
		}
		tmp[n]='\0';
		printf("%s\n%d\n",tmp,sum);
	}
	return 0;
} 

8.Repeating Decimals  UVA - 202

題目連結:UVA-202

問題描述:
The decimal expansion of the fraction 1/33 is 0.03, where the 03 is used to indicate that the cycle 03 repeats indefinitely with no intervening digits. In fact, the decimal expansion of every rational number (fraction) has a repeating cycle as opposed to decimal expansions of irrational numbers, which have no such repeating cycles.
Examples of decimal expansions of rational numbers and their repeating cycles are shown below. Here, we use parentheses to enclose the repeating cycle rather than place a bar over the cycle.
Write a program that reads numerators and denominators of fractions and determines their repeating cycles.
For the purposes of this problem, define a repeating cycle of a fraction to be the first minimal length string of digits to the right of the decimal that repeats indefinitely with no intervening digits. Thus for example, the repeating cycle of the fraction 1/250 is 0, which begins at position 4 (as opposed to 0 which begins at positions 1 or 2 and as opposed to 00 which begins at positions 1 or 4).
Input
Each line of the input file consists of an integer numerator, which is nonnegative, followed by an integer denominator, which is positive. None of the input integers exceeds 3000. End-of-file indicates the end of input.
Output
For each line of input, print the fraction, its decimal expansion through the first occurrence of the cycle to the right of the decimal or 50 decimal places (whichever comes first), and the length of the entire repeating cycle. In writing the decimal expansion, enclose the repeating cycle in parentheses when possible. If the entire repeating cycle does not occur within the first 50 places, place a left parenthesis where the cycle begins — it will begin within the first 50 places — and place ‘...)’ after the 50th digit.
Sample Input
76 25

5 43

1 397

Sample Output
76/25 = 3.04(0)

     1 = number of digits in repeating cycle

5/43 = 0.(116279069767441860465)

      21 = number of digits in repeating cycle

1/397 = 0.(00251889168765743073047858942065491183879093198992...)

     99 = number of digits in repeating cycle

問題分析:模擬豎式除法,當發現餘數出現過時可以判斷找到了週期

AC程式碼:
 

#include<iostream>
#include<map> 
using namespace std;
int main()
{
	int a,b,frac[10000],cycle,integer;
	while(cin>>a>>b){
		int cnt=0,tmp=a%b;
		integer=a/b;
		map<int,int> ip;//鍵是餘數,值是由該餘數產生的數出現的位置
		ip[tmp]=0;
		while(1){
			tmp*=10;frac[cnt++]=tmp/b;
			tmp=tmp%b;
			if(ip.count(tmp)){cycle=cnt-ip[tmp];break;}
			else ip[tmp]=cnt;
		}
		printf("%d/%d = %d.",a,b,integer);
		for(int i=0;i<ip[tmp];++i) printf("%d",frac[i]);
		printf("(");
		for(int i=ip[tmp];i<ip[tmp]+50&&i<cnt;++i) printf("%d",frac[i]);
		if(cycle>50) printf("...");
		printf(")\n");
		printf("   %d = number of digits in repeating cycle\n",cycle);
		cout<<endl;
	}
	return 0;
}

9.All in All  UVA - 10340

問題連結:UVA-10340

問題描述:
You have devised a new encryption technique which encodes a message by inserting between its characters randomly generated strings in a clever way. Because of pending patent issues we will not discuss in detail how the strings are generated and inserted into the original message. To validate your method, however, it is necessary to write a program that checks if the message is really encoded in the final string. Given two strings s and t, you have to decide whether s is a subsequence of t, i.e. if you can remove characters from t such that the concatenation of the remaining characters is s.
Input
The input contains several testcases. Each is specified by two strings s, t of alphanumeric ASCII characters separated by whitespace. Input is terminated by EOF.
Output
For each test case output, if s is a subsequence of t.
Sample Input
sequence subsequence

person compression

VERDI vivaVittorioEmanueleReDiItalia

caseDoesMatter CaseDoesMatter
Sample Output
Yes

No

Yes

No

問題分析:判斷對於s中的每個字元能否在t中按順序找到

AC程式碼:
 

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s,t;
	while(cin>>s>>t){
		int flag=1,pos=0;
		for(int i=0;i<s.length();++i){
			int fg=0;
			for(int j=pos;j<t.length();++j)
				if(t[j]==s[i]){pos=j+1;fg=1;break;}
			if(!fg){flag=0;break;}
		}
		if(flag) cout<<"Yes\n";
		else cout<<"No\n";
	}
	return 0;
}

10.Box  UVA - 1587

問題連結:UVA-1587

問題描述:

Ivan works at a factory that produces heavy machinery. He has a simple job — he knocks up wooden boxes of different sizes to pack machinery for delivery to the customers. Each box is a rectangular parallelepiped. Ivan uses six rectangular wooden pallets to make a box. Each pallet is used for one side of the box.
Joe delivers pallets for Ivan. Joe is not very smart and often makes mistakes — he brings Ivan pallets that do not fit together to make a box. But Joe does not trust Ivan. It always takes a lot of time to explain Joe that he has made a mistake. Fortunately, Joe adores everything related to computers and sincerely believes that computers never make mistakes. Ivan has decided to use this for his own advantage. Ivan asks you to write a program that given sizes of six rectangular pallets tells whether it is possible to make a box out of them.
Input
Input file contains several test cases. Each of them consists of six lines. Each line describes one pallet and contains two integer numbers w and h (1 ≤ w,h ≤ 10000) — width and height of the pallet in millimeters respectively.
Output
For each test case, print one output line. Write a single word ‘POSSIBLE’ to the output file if it is possible to make a box using six given pallets for its sides. Write a single word ‘IMPOSSIBLE’ if it is not possible to do so.
Sample Input
1345 2584 2584 683 2584 1345 683 1345 683 1345 2584 683 1234 4567 1234 4567 4567 4321 4322 4567 4321 1234 4321 1234

Sample Output
POSSIBLE IMPOSSIBLE

問題分析:八種情況

AC程式碼:
 

#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
int main()
{
	int tmpw,tmph,cnt=0,w[6],h[6],vis[6];
	vector<int> index;
	while(cin>>tmpw>>tmph){
		if(tmpw<tmph){//將w,h按大小後儲存 
			int tmp=tmpw;
			tmpw=tmph;tmph=tmp;
		}
		w[cnt]=tmpw;h[cnt++]=tmph;
		if(cnt!=6) continue; 
		cnt=cnt%6;
		memset(vis,0,sizeof(vis));index.clear();
		int flag=1;
		//將三個面提取出來 
		for(int i=0;i<6;++i)
			if(!vis[i]){
				int fg=0;
				vis[i]=1;
				for(int j=0;j<6;++j)
					if(w[j]==w[i]&&h[i]==h[j]&&!vis[j]){fg=1;index.push_back(i);vis[j]=1;break;}
				if(!fg){flag=0;break;}
			}
		if(!flag){printf("IMPOSSIBLE\n");continue;}//如果有的面找不出來則不能形成長方體 
		int fg=0;
		if(w[index[0]]==w[index[1]]&&h[index[0]]==w[index[2]]&&h[index[1]]==h[index[2]]) fg=1;
		else if(w[index[0]]==w[index[1]]&&h[index[0]]==h[index[2]]&&h[index[1]]==w[index[2]]) fg=1;
		else if(w[index[0]]==h[index[1]]&&h[index[0]]==h[index[2]]&&w[index[1]]==w[index[2]]) fg=1;
		else if(w[index[0]]==h[index[1]]&&h[index[0]]==w[index[2]]&&w[index[1]]==h[index[2]]) fg=1;
		else if(h[index[0]]==w[index[1]]&&w[index[0]]==h[index[2]]&&h[index[1]]==w[index[2]]) fg=1;
		else if(h[index[0]]==w[index[1]]&&w[index[0]]==w[index[2]]&&h[index[1]]==h[index[2]]) fg=1;
		else if(h[index[0]]==h[index[1]]&&w[index[0]]==h[index[2]]&&w[index[1]]==w[index[2]]) fg=1;
		else if(h[index[0]]==h[index[1]]&&w[index[0]]==w[index[2]]&&w[index[1]]==h[index[2]]) fg=1;
		if(fg) printf("POSSIBLE\n");
		else printf("IMPOSSIBLE\n");
	}
	return 0;
}

11.Kickdown  UVA - 1588

問題連結:UVA-1588

問題描述:
A research laboratory of a world-leading automobile company has received an order to create a special transmission mechanism, which allows for incredibly efficient kickdown — an operation of switching to lower gear. After several months of research engineers found that the most efficient solution requires special gears with teeth and cavities placed non-uniformly. They calculated the optimal flanks of the gears. Now they want to perform some experiments to prove their findings. The first phase of the experiment is done with planar toothed sections, not round-shaped gears. A section of length n consists of n units. The unit is either a cavity of height h or a tooth of height 2h. Two sections are required for the experiment: one to emulate master gear (with teeth at the bottom) and one for the driven gear (with teeth at the top).
There is a long stripe of width 3h in the laboratory and its length is enough for cutting two engaged sections together. The sections are irregular but they may still be put together if shifted along each other.
The stripe is made of an expensive alloy, so the engineers want to use as little of it as possible. You need to find the minimal length of the stripe which is enough for cutting both sections simultaneously.
Input
The input file contains several test cases, each of them as described below. There are two lines in the input, each contains a string to describe a section. The first line describes master section (teeth at the bottom) and the second line describes driven section (teeth at the top). Each character in a string represents one section unit — 1 for a cavity and 2 for a tooth. The sections can not be flipped or rotated. Each string is non-empty and its length does not exceed 100.
Output
For each test case, write to the output a line containing a single integer number — the minimal length of the stripe required to cut off given sections.
Sample Input
2112112112

2212112

12121212

21212121

2211221122

21212
Sample Output
10

8

15

問題分析:木板可以左右移動,動的木板可以是第一塊也可以是第二塊

AC程式碼:
 

#include<iostream>
#include<algorithm>
using namespace std; 
int solve(string a,string b)//b在a上右移時得到的解
{
	int pos=a.size();
	for(int i=0;i<a.size();++i){
		int flag=1;
		for(int j=0;i+j<a.size()&&j<b.size();++j)
			if(a[i+j]-'0'+b[j]-'0'>3) {flag=0;break;}
		if(flag){pos=i;break;}
	}
	return max(a.size(),pos+b.size());
}
int main()
{
	string a,b;
	while(cin>>a){
		cin>>b;
		int sum=solve(a,b);
		sum=min(sum,solve(b,a));
		reverse(a.begin(),a.end());reverse(b.begin(),b.end());
		sum=min(min(sum,solve(a,b)),solve(b,a));
		printf("%d\n",sum);
	}
	return 0;
} 

12.Floating-Point Numbers  UVA - 11809

題目連結:UVA-11809

題目描述:
Floating-point numbers are represented differently in computers than integers. That is why a 32-bit floating-point number can represent values in the magnitude of 1038 while a 32-bit integer can only represent values as high as 232. Although there are variations in the ways floating-point numbers are stored in Computers, in this problem we will assume that floating-point numbers are stored in the following way:
Floating-point numbers have two parts mantissa and exponent. M-bits are allotted for mantissa and E bits are allotted for exponent. There is also one bit that denotes the sign of number (If this bit is 0 then the number is positive and if it is 1 then the number is negative) and another bit that denotes the sign of exponent (If this bit is 0 then exponent is positive otherwise negative). The value of mantissa and exponent together make the value of the floating-point number. If the value of mantissa is m then it maintains the constraints 1 2 ≤ m < 1. The left most digit of mantissa must always be 1 tomaintain the constraint 1 2 ≤ m < 1. So this bit is not stored as it is always 1. So the bits in mantissa actually denote the digits at the right side of decimal point of a binary number (Excluding the digit just to the right of decimal point) In the figure above we can see a floating-point number where M = 8 and E = 6. The largest value this floating-point number can represent is (in binary) 0.1111111112×21111112. The decimal equivalent to this number is: 0.998046875×263 = 920535763834529382410. Given the maximum possible value represented by a certain floating point type, you will have to find how many bits are allotted for mantissa (M) and how many bits are allotted for exponent (E) in that certain type.
Input
The input file contains around 300 line of input. Each line contains a floating-point number F that denotes the maximum value that can be represented by a certain floating-point type. The floating point number is expressed in decimal exponent format. So a number AeB actually denotes the value A×10B. A line containing ‘0e0’ terminates input. The value of A will satisfy the constraint 0 < A < 10 and will have exactly 15 digits after the decimal point.
Output
For each line of input produce one line of output. This line contains the value of M and E. You can assume that each of the inputs (except the last one) has a possible and unique solution. You can also assume that inputs will be such that the value of M and E will follow the constraints: 9 ≥ M ≥ 0 and 30 ≥ E ≥ 1. Also there is no need to assume that (M + E + 2) will be a multiple of 8.
Sample Input
5.699141892149156e76

9.205357638345294e18

0e0
Sample Output
5 8

8 6

問題分析:我是真的菜。。。光想著用大數直接做,忘了取對數,eps取成e-7就一直wa

AC程式碼:

#include<iostream>
#include<cmath>
using namespace std;
const double eps=1e-5;
int main()
{
	double a,b;
	int m,e;
	while(scanf("%17lfe%lf",&a,&b)){
		if(a<eps) break;
		a=log(a)+b*log(10);
		int flag=0;
		for(int i=0;i<10;++i){
			double tmp=0;
			for(int j=1;j<=i+1;++j) tmp+=1.0/pow(2,j);
			for(int j=1;j<=30;++j)
				if(fabs(a-log(tmp)-(pow(2,j)-1)*log(2))<eps)
					cout<<i<<" "<<j<<endl;
		}
	}
	return 0;
}