標籤:pid cst problem getch 整數 print 描述 空格 har
此文為博主原創題解,轉載時請通知博主,並把原文連結放在本文醒目位置。
題目連結:https://www.luogu.org/problem/show?pid=1765
題目描述
一般的手機的鍵盤是這樣的:
1 2 abc 3 def
4 ghi 5 jkl 6 mno
7 pqrs 8 tuv 9 wxyz
* 0 #
要按出英文字母就必須要按數字鍵多下。例如要按出x就得按9兩下,第一下會出w,而第二下會把w變成x。0鍵按一下會出一個空格。
你的任務是讀取若干句只包含英文小寫字母和空格的句子,求出要在手機上打出這個句子至少需要按多少下鍵盤。
輸入輸出格式
輸入格式:
一行一個句子,只包含英文小寫字母和空格,且不超過200個字元。
輸出格式:
一行一個整數,表示按鍵盤的總次數。
輸入輸出範例
輸入範例#1:
i have a dream
輸出範例#1:
23
說明
_NOI導刊2010普及(10)
分析:
這題非常水...只是讀入的時候用了cin.getline(),之前從來沒用過。
cin.getline(字串名稱,最大可能長度,結束符);
其中結束符如果不特別指定,預設為‘\n‘,也就是分行符號。這樣就可以自由讀入空格,或者實現其他讀入要求。
AC代碼:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 6 using namespace std; 7 8 inline void read(int &x) 9 {10 x = 0;char ch = getchar(), c = ch;11 while(ch < ‘0‘ || ch > ‘9‘)c = ch, ch = getchar();12 while(ch <= ‘9‘ && ch >= ‘0‘)x = (x<<1)+(x<<3)+ch - ‘0‘, ch = getchar();13 if(c == ‘-‘)x = -x;14 }15 16 int cnt[30] = {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};17 //數組的正確使用(誤)18 char line[1005];19 20 int main()21 {22 int ans = 0;23 cin.getline(line,1000,‘\n‘);24 int len = strlen(line);25 for(int i = 0;i < len;++ i)26 {27 if(line[i] >= ‘a‘ && line[i] <= ‘z‘)28 ans += cnt[line[i]-‘a‘];29 else if(line[i] == ‘ ‘)30 ans += 1;31 }32 printf("%d\n",ans);33 return 0;34 }
洛穀 P1765 手機_NOI導刊2010普及(10) 題解