close

 

CPE一顆星考題:

1.Vito's family

Time Limit: 3 sec

Background

The world-known gangster Vito Deadstone is moving to New York. He has a very big family there, all of them living in Lamafia Avenue. Since he will visit all his relatives very often, he is trying to find a house close to them.

Description

Vito wants to minimize the total distance to all of them and has blackmailed you to write a program that solves his problem.

 

題意是要算出Vito Deadstoney到各個親戚家的最短距離

取陣列最中間的街號來計算會得出最佳值

1.先輸入要測試的筆數

2.輸入親戚的個數

3.輸入親戚的街號

4.將親戚街號照順序排列

5.取得中位數

6.迴圈加總 : 絕對值(親戚家街號-中位數街號)

7.印出結果

#include<iostream>                // 是C++中用於數據的流式輸入與輸出的頭文件 
#include<algorithm>
#include<vector>
using namespace std;              //將cout,cin,endl設為std
vector<int> num;                  //vector為容器陣列用的函式

int main(){
  int l,c,k;                      //三個變數分別為,測試資料的筆數、親戚個數、親戚街號
  cin >> l;
  while(l--){
    cin >> c;
    num.clear();                  //要記得清除num再開始迴圈
    for(int i = 0;i < c;i++){
      cin >> k;
      num.push_back(k);           //將新的街號加到num陣列
    }
    sort(num.begin(),num.end());  //將num陣列由小到大排序
    int mid = num[c/2];           //取中位數(陣列最中間的數值)
    int sum = 0;
    for(int i = 0;i < c;i++){
      sum+=abs(num[i]-mid);       //迴圈加總
    }
    cout << sum << endl;          //印出最佳值
  }
  return 0;
}

 

 

 

2.Hashmat the brave warrior

Time Limit: 3 sec

Description

Hashmat is a brave warrior who with his group of young soldiers moves from one place to another to fight against his opponents. Before fighting he just calculates one thing, the difference between his soldier number and the opponent's soldier number. From this difference he decides whether to fight or not. Hashmat's soldier number is never greater than his opponent.

Input

The input contains two integer numbers in every line. These two numbers in each line denotes the number of soldiers in Hashmat's army and his opponent's army or vice versa. The input numbers are not greater than 2^32. Input is terminated by End of File.

Output

For each line of input, print the difference of number of soldiers between Hashmat's army and his opponent's army. Each output should be in seperate line.

 

題意是要算出 兩隊士兵人數的相差

使用絕對值abs( ) ,先導入 <cstdlib>才能使用

因為要2的32次方,所以要用long long才能儲存的下

 

#include<iostream>
#include<cstdlib>
using namespace std;
long long a,b;
int main(){
 
  while(cin>>a>>b){            //用迴圈的方式輸入每筆資料
    cout<<abs(a-b)<<endl;
  }
  return 0;
}
    

 

 

 

3.Primary Arithmetic

Time Limit: 3 sec

Description

Children are taught to add multi-digit numbers from right-to-left one digit at a time. Many find the "carry" operation - in which a 1 is carried from one digit position to be added to the next - to be a significant challenge. Your job is to count the number of carry operations for each of a set of addition problems so that educators may assess their difficulty.

Input

Each line of input contains two unsigned integers less than 10 digits. The last line of input contains 0 0.

Output

For each line of input except the last you should compute and print the number of carry operations that would result from adding the two numbers, in the format shown below.

題意是要算兩個不超過10的10次方的正整數相加的進位次數

先自訂一個divide函式,將數字分解後存入陣列arr[]中,同時將數字的位數存入cnt中

迴圈一圈一圈的從最後的位數開始相加

(詳細過程待補)

最後印出結果

#include <iostream>
#include <algorithm>     //要用到max函數
using namespace std;
void divide(int n,int arr[],int &cnt){    //用viod宣告的自訂函數 可以不需要回傳值
  for(cnt = 0;n != 0;cnt++){
    arr[cnt]=n%10;
    n/=10;               // n = n/10
  }
}



int main(){
  int a,b;
  while(cin>>a>>b && (a!=0||b!=0)){
    int lenA, lenB;
    int arrA[11]={},arrB[11]={};
    int sum[12]= {};
    divide(a,arrA,lenA);
    divide(b,arrB,lenB);
    int lenM=max(lenA,lenB);  //比大小,取大的使用,減少運算次數
    int ans = 0;
    for(int i=0;i<lenM;++i){
    sum[i] = sum[i] + (arrA[i]+arrB[i]);    //可能讀到有被加1的sum[i]
      if(sum[i]>=10){
        sum[i] = sum[i] - 10;     
        sum[i+1] = sum[i+1] + 1;  //進位後,幫下一個位數的數字+1
        ans = ans + 1;
      }
    }
    if(ans==0)
      cout<<"No carry operation.\n";
    else if(ans==1)
      cout<<"1 carry operation.\n";
    else
      cout<<ans<<" carry operations.\n";
    
  }
  return 0;
}
    

※輸出結果的字串,不要複製正確輸出的直接使用!最前面跑出莫名其妙的"?",害我不知道哪裡有問題...

 

 

 

4.The 3n+1 Problem

題意:

考拉茲臆測:指輸入一個正整數,如果是奇數將它乘3在加1,如果是偶數,將它除以2。如此循環最終能得到 1

而其中經過的計算次數稱為考拉茲長度

本題則要輸入一組測試資料,輸出裡面考拉茲長度最長的結果

例如輸入測資為1~10,9的考拉茲長度為20,是裡面最長的,答案則為9

 

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
  int a,b;
  while(cin>>a>>b){
    cout<<a<<" "<<b<<" ";
    if(a>b){
      int c=a;a=b;b=c;}
    int maxLen=0;
    for(int k=a;k<=b;k++){
      int n=k;int len=1;
      while(true){
        if(n==1)
          break;
        if(n%2)      //如果n%2有餘數,則n=n*3+1
          n=n*3+1;
        else n=n/2;  //如果沒餘數則執行else,n=n/2
        len++;
      }
      maxLen = max(maxLen,len);
    }
    cout<<maxLen<<endl;
  }
  return 0;
}
    
    

 

 

5.You can say 11

題意:

整數的奇數為相加減偶數位相加若為0或11的倍數,則該數為11的倍數

數入的數字可能會是00開頭,所以必須輸入字串變數來儲存變數,以保留開頭的0

#include <iostream>
#include <string>
using namespace std;
int main(){
  string a;
  while(cin>>a && a!="0"){
    long long sum[2] = {0,0};       //初始化要在迴圈內!!
    for(int i=0;i<a.length();i++){
      sum[i%2] = sum[i%2]+a[i]-48;  //會分為"sum[0](整除)"或"sum[1](餘1)"
                                    //字串'0'的數值為48,所以必須扣除掉,或是直接 -'0'
    }

    if((sum[0]-sum[1])%11)
      cout<<a<<" is not a multiple of 11."<<endl;
    else
      cout<<a<<" is a multiple of 11."<<endl;
      
  }
  return 0;
}
    

 

 

6.List of Conquests

Time Limit: 2 sec

Description

In Act I, Leporello is telling Donna Elvira about his master's long list of conquests:

``This is the list of the beauties my master has loved, a list I've made out myself: take a look, read it with me. In Italy six hundred and forty, in Germany two hundred and thirty-one, a hundred in France, ninety-one in Turkey; but in Spain already a thousand and three! Among them are country girls, waiting-maids, city beauties; there are countesses, baronesses, marchionesses, princesses: women of every rank, of every size, of every age.'' (Madamina, il catalogo è questo)

As Leporello records all the ``beauties'' Don Giovanni ``loved'' in chronological order, it is very troublesome for him to present his master's conquest to others because he needs to count the number of ``beauties'' by their nationality each time. You are to help Leporello to count.

Input

The input consists of at most 2000 lines, but the first. The first line contains a number n, indicating that there will be n more lines. Each following line, with at most 75 characters, contains a country (the first word) and the name of a woman (the rest of the words in the line) Giovanni loved. You may assume that the name of all countries consist of only one word.

Output

The output consists of lines in alphabetical order. Each line starts with the name of a country, followed by the total number of women Giovanni loved in that country, separated by a space.

題意是要算出國家在資料裡出現在次數並計數

先輸入有幾筆資料後,接著輸入各國與人名

標準輸入串
正確輸出串  
England 5↵\r\n
Spain 5↵\r\n

 

#include <iostream>
#include <string>
#include <map>
using namespace std;
int main(){
  map<string,int> count;
  map<string,int> ::iterator iter;
  string first_s;
  char other[76]={0};
  int n;
  cin >> n;
  cin.ignore();
  while(n--){
    cin >> first_s;
    count[first_s]++;
    cin.getline(other,76);
  }
  for(iter=count.begin();
      iter!=count.end();iter++){
    cout<<iter->first<<" ";
    cout<<iter->second<<endl;
  }
  return 0;
}

 

 

7.What's Cryptanalysis?

Time Limit: 3 sec

Description

Cryptanalysis is the process of breaking someone else's cryptographic writing. This sometimes involves some kind of statistical analysis of a passage of (encrypted) text. Your task is to write a program which performs a simple analysis of a given text.

Input

The first line of input contains a single positive decimal integer n. This is the number of lines which follow in the input. The next n lines will contain zero or more characters (possibly including whitespace). This is the text which must be analyzed.

Output

Each line of output contains a single uppercase letter, followed by a single space, then followed by a positive decimal integer. The integer indicates how many times the corresponding letter appears in the input text. Upper and lower case letters in the input are to be considered the same. No other characters must be counted. The output must be sorted in descending count order; that is, the most frequent letter is on the first output line, and the last line of output indicates the least frequent letter. If two letters have the same frequency, then the letter which comes first in the alphabet must appear first in the output. If a letter does not appear in the text, then that letter must not appear in the output.

題意,將輸入的字串,字母由多到少,由A到Z排列

標準輸入串

 

正確輸出串  
S 7↵\r\n
T 6↵\r\n
I 5↵\r\n
E 4↵\r\n
O 3↵\r\n
A 2↵\r\n
H 2↵\r\n
N 2↵\r\n
U 2↵\r\n
W 2↵\r\n
C 1↵\r\n
M 1↵\r\n
Q 1↵\r\n
Y 1↵\r\n

 

#include <iostream>
#include <cctype>                     //單位元組字元處理
using namespace std;

int main(){ 
  int count[256]={},len=0; 
  char c;
  while(cin>>c){                     //每輸入一個字元,長度增加1
    len++;
    count[toupper(c)]++;             //將字母統一為大寫
  }
  while (--len){                     //先扣掉1,以免輸出出現0次的字元
    for (c='A';c<='Z';c++){          //排序
      if(count[c]==len)              //會先輸出出現最多次的字元
        cout<<c<<" "<<len<<endl;
    }
  }
  return 0;
}

 

 

8.Decode the Mad

題意:解碼,將輸入的字串,改為對應鍵盤左邊第二個字元

 

標準輸入串
正確輸出串  
how are you↵\r\n

 

使用strchr函式,從字串中找出字元的位置

#include <iostream>
#include <cstring>
#include <cstdio>             //字符計算
using namespace std;
int main(){
 char c,s[]="`1234567890-="   //建立鍵盤表
 "qwertyuiop[]\\"             //表示\用跳脫字元\所以有兩條
 "asdfghjkl;'zxcvbnm,./";  
 while(cin.get(c)){           //輸入整行包含空白
  c = tolower(c);             //將英文大寫都轉換為小寫
  char *p=strchr(s,c);        //利用strchr函式找出對應表中的位置
  if (p!=0)
    cout<<*(p-2);             //依題目格式往左兩格
  else
    cout<<c;                  //若不再表中,則照原樣輸出(空白、符號)
  }
  return 0;
}
    

 

 

 

9.Summing Digits

題意:一個數學函式f(n)

將該字串所有數字相加得新數字

重複直到只剩下一個數字稱為g(n)

標準輸入串
正確輸出串  
2↵\r\n
2↵\r\n
2↵\r\n
2↵\r\n
2↵\r\n
4↵\r\n
1↵\r\n
5↵\r\n
3↵\r\n
6↵\r\n
5↵\r\n
2↵\r\n
4↵\r\n
9↵\r\n
2↵\r\n

 

本題使用C語言

 

 

#include <stdio.h>
#include <string.h>
int main(int argc,int *argv[]){
  char n[11];
  while(scanf("%s",n)!=EOF && n[0]!=48){
    while(strlen(n)!=1){
      int i=0,F=0;
      for(i=0;i<strlen(n);i++)
        F = F + (n[i]-48);
      memset(n,'\0',11);  //歸零
      sprintf(n,"%d",F);  //轉換為字串
      
    }
    printf("%s\n",n);
  }
  return 0;
}
    

 

 

 

10.Common Permutation

Time Limit: 4 sec

Description

 

Given two strings of lowercase letters, a and b, print the longest string x of lowercase letters such that there is a permutation of x that is a subsequence of a and there is a permutation of x that is a subsequence of b.

Input

Input file contains several lines of input. Consecutive two lines make a set of input. That means in the input file line 1 and 2 is a set of input, line 3 and 4 is a set of input and so on. The first line of a pair contains a and the second contains b. Each string is on a separate line and consists of at most 1000 lowercase letters.

Output

For each set of input, output a line containing x. If several x satisfy the criteria above, choose the first one in alphabetical order.

題意:輸入兩字串a、b,把兩字串擁有相同的單字印出來,並從a到z排列,若沒有該字元則跳過

1.統計兩個字串所有a至z字元個數

2.按照a至z的順序,印出字元(若count_a[i]=0就不會印出任何字元)

3.處理玩一組測資則換行

 

標準輸入串
正確輸出串  
e↵\r\n
nw↵\r\n
et↵\r\n

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
  char a[1001],b[1001];
  int count_a[123],count_b[123];
  int i,j;
  while(gets(a)){
    memset(count_a,0,sizeof(count_a));
    memset(count_b,0,sizeof(count_b));
    for(i=0;i<strlen(a);i++)   //注意,for迴圈若沒用大括號,也不需要';'結尾
      count_a[a[i]]++;
    gets(b);
    for(i=0;i<strlen(b);i++)
      count_b[b[i]]++;
    for(i=97;i<123;i++){
      j=0;                                  //要在這個回圈內初始化
      while(j<count_a[i] && j<count_b[i]){  //j從0開始,如果count_a[i]和count_b[i]有數字就會印出來,如果沒有數字(=0)就會跳過
        printf("%c",i);
        j++;
      }
    }
      printf("\n");
  }
  return 0;
}
    

 

 

11.Rotating Sentences

Time Limit: 3 sec

Description

In ``Rotating Sentences,'' you are asked to rotate a series of input sentences 90 degrees clockwise. So instead of displaying the input sentences from left to right and top to bottom, your program will display them from top to bottom and right to left.

Input

As input to your program, you will be given a maximum of 100 sentences, each not exceeding 100 characters long. Legal characters include: newline, space, any punctuation characters, digits, and lower case or upper case English letters. (NOTE: Tabs are not legal characters.)

Output

The output of the program should have the last sentence printed out vertically in the leftmost column; the first sentence of the input would subsequently end up at the rightmost column.

 

題意:將句子改成由左至右,由上而下輸出,多餘的部分要補空白

標準輸入串
正確輸出串  
"R↵\r\n
Ie↵\r\n
 n↵\r\n
te↵\r\n
h ↵\r\n
iD↵\r\n
ne↵\r\n
kc↵\r\n
,a↵\r\n
 r↵\r\n
tt↵\r\n
he↵\r\n
es↵\r\n
r ↵\r\n
eo↵\r\n
fn↵\r\n
oc↵\r\n
re↵\r\n
e ↵\r\n
 s↵\r\n
Ia↵\r\n
 i↵\r\n
ad↵\r\n
m,↵\r\n
.↵\r\n
"↵\r\n

 

#include <iostream>
#include <cstring>
using namespace std;
int main(){
  char str[100][101];       //最多100行,每行最多100個字元
  int len[100],n=0,max=0;
  for(int i=0;i<100;i++){
    for(int j=0;j<101;j++){
      str[i][j]=0;
      len[n]=0;
    }
  }
  while(cin.getline(str[n],101)){
    len[n]=strlen(str[n]);
    if(len[n]>max)
      max = len[n];
    for(int add=len[n];add<max;add++){
      str[n][add]=' ';
      len[n]++;
    }
    n++;
  }
  for(int j=0;j<max;j++){
    for(int i=n-1;i>=0;i--)
      if(j<len[i])
        cout<<str[i][j];
    cout<<endl;
    
  }
  return 0;
}

 

12.TeX Quotes

題意:將該字串,第一個"改為``,第二個"改為''

標準輸入串
正確輸出串  
``To be or not to be,'' quoth the Bard, ``that↵\r\n
is the question''.↵\r\n
The programming contestant replied: ``I must disagree.↵\r\n
To `C' or not to `C', that is The Question!''↵\r\n

 

#include <iostream>
using namespace std;
int main(){
  char c,k=0;                 //k計算"的個數
  while(cin.get(c)){          //輸入整個字串包含符號空白
    if(c!='"') cout<<c;   
    else{                     //如果遇到"
      k=k+1;                  //遇到就+1算個數
      if (k%2==0) cout<<"''"; //除以2餘0即為偶數,為排在後面的"
      else cout<<"``";        //反之就是前面的"
    }
  }
  return 0;
}

 

 

13.Doom's Day Algorithm

Time Limit: 5 sec

Background

No. Doom's day algorithm is not a method to compute which day the world will end. It is an algorithm created by the mathematician John Horton Conway, to calculate which day of the week (Monday, Tuesday, etc.) corresponds to a certain date.

This algorithm is based in the idea of the doomsday, a certain day of the week which always occurs in the same dates. For example, 4/4 (the 4th of April), 6/6 (the 6th of June), 8/8 (the 8th of August), 10/10 (the 10th of October) and 12/12 (the 12th of December) are dates which always occur in doomsday. All years have their own doomsday.

In year 2011, doomsday is Monday. So all of 4/4, 6/6, 8/8, 10/10 and 12/12 are Mondays. Using that information, you can easily compute any other date. For example, the 13th of December 2011 will be Tuesday, the 14th of December 2011 will be Wednesday, etc.

Description

Other days which occur on doomsday are 5/9, 9/5, 7/11 and 11/7. Also, in leap years, we have the following doomsdays: 1/11 (the 11th of January) and 2/22 (the 22nd of Febrary), and in non-leap years 1/10 and 2/21.

Given a date of year 2011, you have to compute which day of the week it occurs.

Input

The input can contain different test cases. The first line of the input indicates the number of test cases.

For each test case, there is a line with two numbers: M D. M represents the month (from 1 to 12) and D represents the day (from 1 to 31). The date will always be valid.

Output

For each test case, you have to output the day of the week where that date occurs in 2011. The days of the week will be: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.

 

題意:給日期算出是星期幾

1.根據題目測資推算,2011/01/06是星期四,所以2010/12/31是星期五,並以此為起點

2.(迴圈算出月份總天數,再加上該月已過的天數),除以7,若餘數為0,則該日為星期日


Sample Input

Sample Output

   

8

1 6

2 28

4 5

5 26

8 1

11 1

12 25

12 31

Thursday

Monday

Tuesday

Thursday

Monday

Tuesday

Sunday

Saturday

 

#include <iostream>
using namespace std;
int main(){
  char week[7][10]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};  //從星期日開始
  int n;
  int Month[]={31,28,31,30,31,30,31,31,30,31,30,31};
  cin>>n;
  while(n--){
    int k=5;                     //起始值(由1/1日星期幾校正)
    int month,day;
    cin>>month>>day;
    for(int i=1;i<month;i++)
      k=k+Month[i-1];            //month個月的天數加總,再加上起始值
    k=(k+day)%7;                 //month個月的天數加總+起始值+此次輸入的day值)除以7取得餘數
    cout<<week[k]<<endl;
  }
  return 0;
}
     

 

14.Jolly Jumpers

Time Limit: 3 sec

Description

A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between successive elements take on all the values 1 through n-1. For instance,

1 4 2 3

is a jolly jumper, because the absolutes differences are 3, 2, and 1 respectively. The definition implies that any sequence of a single integer is a jolly jumper. You are to write a program to determine whether or not each of a number of sequences is a jolly jumper.

Input

Each line of input contains an integer n <= 3000 followed by n integers representing the sequence.

Output

For each line of input, generate a line of output saying "Jolly" or "Not jolly".


Sample Input

Sample Output

Sample IO Generation

     

4 1 4 2 3

5 1 4 2 -1 6

Jolly

Not jolly

IO Generation(tested feature)

 

題意:

一數列,將所有相隔兩數絕對值差,放入一新數列

3,2,3,5 間格差1,3,2,恰為{1,2,3},則該數列可稱為Jolly

#include <iostream>
#include <set>
using namespace std;
int main(){
  int n;
  while(cin>>n){
    set<int> tank;
    int a;cin>>a;
    for(int i=1;i<n;i++){
      int b;cin>>b;
      int d=(b-a<0?a-b:b-a);
      
      if(d && d<n)tank.insert(d);
      a=b;
    }
    if(tank.size()==n-1)cout<<"Jolly";
    else  cout<<"Not jolly";
    cout << endl;
  }
  return 0;
}
    

 

 

 

 

10453:Odd Sum

Time Limit: 3 sec

Description

Given a range [a, b], you are to find the summation of all the odd integers in this range. For example, the summation of all the odd integers in the range [3, 9] is

3 + 5 + 7 + 9 = 24.

Input

There can be at multiple test cases. The first line of input gives you the number of test cases,T (1 ≤ T≤ 100). Then T test cases follow. Each test case consists of 2 integers a and b (0 a ≤ b ≤100) in two separate lines.

Output

For each test case you are to print one line of output - the serial number of the test case followed by the summation of the odd integers in the range [a, b].

題意:先輸入有幾組,再輸入兩數字,兩數之間的所有奇數,做等差數列相加,再用Case格式輸出


Sample Input

Sample Output

Sample IO Generation

     

2

1

5

3

5

Case 1: 9

Case 2: 8

IO Generation(tested feature)

 

#include <iostream>
using namespace std;
int main(){
  int d,a,b,c,s; //d有幾筆資料,a、b為兩數字,c為項數,s為數列合
  int ans=0;     //幫case計數
  cin>>d;
  while(d--){
  while(cin>>a>>b){
    if(a%2==0)
      a++;
    if(b%2==0)
      b--;
    c = ((b-a)/2)+1;
    s =c*(a+b)/2;
    ans++;
    cout<<"Case "<<ans<<": "<<s<<endl;
    
    }
    
  }
  return 0;
}

 

 

arrow
arrow
    全站熱搜

    ivankao 發表在 痞客邦 留言(0) 人氣()