(C語言)ACM中的資料處理問題!
阿新 • • 發佈:2019-01-26
ACM競賽題目的輸入資料常要求有多組,並且格式多種多樣,這是初次登OJ平臺的同學的一個障礙。實際上,這些格式可以歸為固定的幾種型別,本文介紹各種型別的處理方法,以幫助同學們克服這些障礙。
實際上,這些模式不僅是OJ平臺上做題的需要。在平時的自由程式設計練習中,也可以自行使用這些模式,以提高除錯程式的效率。對程式測試的意識也將在此過程中得到提升。本文1-4部分介紹了幾種型別輸入的處理,第5部分介紹通過輸入重定向提高除錯程式效率的方法。
1. 最簡單的輸入
例1:
[plain] view plaincopyprint?
- Description
- 計算 a+b
-
Input
- 兩個整數 a,b
- Output
- a+b的值
- Sample Input
- 1 2
- Sample Output
- 3
[cpp] view plaincopyprint?
- #include <stdio.h>
- int main()
- {
- int a,b;
- scanf("%d %d",&a, &b);
- printf("%d\n",a+b); //對其他題目,換成要求的複雜處理與輸出
-
return
- }
2. 一次執行,要輸入多組資料,直到讀至輸入檔案末尾(EOF)為止
例2:
[plain] view plaincopyprint?
- Description
- 計算 a + b
- Input
- 多組由兩個整數(a和b)構成的輸入,a和b之間用空格隔開,每組輸入單獨佔一行
- Output
- 每組的兩個整數(a和b)求和並輸出,每組的求和結果獨佔一行
- Sample Input
- 1 5
- 10 20
- 400 516
- Sample Output
- 6
- 30
- 916
[cpp] view plaincopyprint?
- #include <stdio.h>
- int main()
- {
- int a,b;
- while(scanf("%d %d",&a, &b) != EOF) // 輸入結束時,scanf函式返回值為EOF(-1),即沒有資料輸入時會退出while迴圈
- {
- printf("%d\n",a+b);
- }
- return 0;
- }
3. 一次執行,要輸入多組資料,組數由第一個輸入資料決定(在開始的時候輸入一個N,接下來是N組資料)
例3:
[plain] view plaincopyprint?
- Description
- 計算 a + b
- Input
- 第一行是資料的組數N,從第二行是N組由兩個整數(a和b)構成的輸入,a和b之間用空格隔開,每組輸入單獨佔一行
- Output
- 每組的兩個整數(a和b)求和並輸出,每組的求和結果獨佔一行
- Sample Input
- 2
- 1 5
- 10 20
- Sample Output
- 6
- 30
[cpp] view plaincopyprint?
- #include<stdio.h>
- int main()
- {
- int n,i;
- int a,b;
- scanf("%d",&n);
- for(i=0;i<n;i++)
- {
- scanf("%d%d",&a,&b);
- printf("%d\n",a+b);
- }
- return 0;
- }
4. 輸入不說明有多少組資料,但以某個特殊輸入為結束標誌。平時做題中常見諸如“輸入學生成績,以-1結束”,沒有學生得-1分的,這個結束資料可以要得。
例4:
[plain] view plaincopyprint?
- Description
- 計算 a + b
- Input
- 多組由兩個整數(a和b)構成的輸入,a和b之間用空格隔開,每組輸入單獨佔一行。當輸入為 0 0 時,輸入結束。
- Output
- 每組的兩個整數(a和b)求和並輸出,每組的求和結果獨佔一行。
- Sample Input
- 1 5
- 10 20
- 0 0
- Sample Output
- 6
- 30
[cpp] view plaincopyprint?
- #include <stdio.h>
- int main()
- {
- int a,b;
- while(scanf("%d %d",&a, &b) &&(a||b))
- {
- printf("%d\n",a+b);
- }
- return 0;
- }
有關字元和字串資料的輸入,在此不再多講,只要將相關的函式用好即可,也可以找到相關資料參考。
5. 利用檔案重定向提高除錯效率
程式設計得到正確結果前,往往需要多次執行程式,每次執行都需要花費不少的時間從鍵盤輸入資料。每次輸入的資料都是相同的時,會給人的心理帶來不爽的感覺,並造成時間上的浪費。無論平時練習還是ACM競賽實戰,這些都是可以避免的。方法是,運用重定向。
用下面的形式呼叫函式freopen()會將標準輸入stdin重定向到檔案input.txt(這個名字可以自己定義)。
[cpp] view plaincopyprint?
- freopen("input.txt","r",stdin); //設定輸入和輸出檔案
[cpp] view plaincopyprint?
- #include<stdio.h>
- int main()
- {
- freopen("input.txt","r",stdin); //只加這一句輸入將被重定向到檔案input.txt
- int a,b;
- scanf("%d%d",&a,&b);
- printf("%d\n",a+b);
- return 0;
- }
需要注意的是,除錯通過的程式,千萬不要直接提交到OJ平臺上去。如果競賽中這樣做了,罰你的20分鐘不要算到我的頭上。提交的程式要把輸入重定向的一行刪除,這樣才算是符合要求的,可以獲得AC的程式。
除了刪除那一行,還有一種簡單的做法是,提交前將這一行前加上註釋符"//",效果是一樣的。
[cpp] view plaincopyprint?- #include<stdio.h>
- int main()
- {
- //freopen("input.txt","r",stdin); //只加這一句輸入將被重定向到檔案input.txt
- int a,b;
- scanf("%d%d",&a,&b);
- printf("%d\n",a+b);
- return 0;