2014年2月22日 星期六

UVA 10008 c++

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=949

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int n,len,temp;
while (cin >> n)
{
int count[26] = { 0 };
char c_temp;
char english[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char input[256];
for (int i = 0; i <= n; i++)
{
cin.getline(input, 256);
len = strlen(input);
for (int j = 0; j <= len; j++)
{
if (input[j] <= 90 && 65 <= input[j])
count[input[j] - 65]++;
else if (input[j] <= 122 && 97<=input[j])
count[input[j] - 97]++;
}
}
for (int i = 0; i <= 25; i++)
{
for (int j = 0; j <= 24; j++)
{
if (count[j]<count[j + 1]) //如果前項大於後項的話交換
{
temp = count[j];
c_temp = english[j];
count[j] = count[j + 1];
english[j] = english[j + 1];
count[j + 1] = temp;
english[j + 1] = c_temp;
}
}
}
for (int i = 0;; i++)
{
if (count[i] == 0)
break;
else
cout << english[i] << " " << count[i] << endl;
}
}
return 0;
}

8 則留言:

  1. 能否請教您 cin.getline 為何要執行 (n+1) 次 而不是n次呢

    回覆刪除
    回覆
    1. 應該是我寫太快寫錯了XD 應該n就可以了~
      麻~管他 反正ACM 他說過了XDD

      刪除
  2. 可是奇怪的點在於如果cin.getline上面的for迴圈
    我改成 for (int i = 1; i <= n; i++)
    執行時是錯誤結果(會少輸入一行字串就直接跳字母累計)
    照你那樣寫才會有正確輸出
    只是我一直想不通為何要跑(n+1)次 ~__~

    回覆刪除
    回覆
    1. 我嘗試了一下.....恩 感覺怪怪的= =||
      他輸入完N之後 會直接跳第一次 ..... 0 然後input 甚麼都沒有 怪怪的

      刪除
    2. http://codepad.org/fvr9gIUF

      刪除
    3. https://drive.google.com/file/d/0BxAW8j_kZs_gWVlVd0JsQlJjQ0U/view?usp=sharing

      刪除
    4. 這是我上PTT問到的結果,所以多一個cin.ignore()清空 buffer

      刪除
    5. 哈哈哈 我現在才看到!!!
      很感謝你的幫助喔^___^

      刪除