2015-04-03 57 views
0

我試着解決谷歌代碼堵塞實踐頁面Minimum Scalar Product中的問題,我用C++編寫的程序,我閱讀常見問題頁面,我們必須測試我們的程序與.in測試文件放在練習頁面上下載,但我不知道如何和我使用UBUNTU 12.04 LTS &請我參加第一次比賽..所以任何幫助將不勝感激..謝謝在提前如何在C++代碼中輸入測試用例在谷歌代碼堵塞

我試圖

#include <vector> 
#include <algorithm> 
#include <iostream> 

using namespace std; 

int main() 
{ 
int numCase; 
cin >> numCase; 
int i, j, n; 
long long c; 
for (i = 0; i < numCase; i++) 
{ 
    cin >> n; 
    vector<long long> array1, array2; 
    for (j = 0; j < n; j++) 
    { 
     cin >> c; 
     array1.push_back(c); 
    } 
    for (j = 0; j < n; j++) 
    { 
     cin >> c; 
     array2.push_back(c); 
    } 
    sort(array1.begin(), array1.end()); 
    sort(array2.begin(), array2.end(), greater<long long>()); 
    long long ans = 0; 
    for (j = 0; j < n; j++) 
     ans += (array1[j] * array2[j]); 
    cout << "Case #" << (i+1) << ": " << ans << endl; 
} 
return 0; 
} 

回答

3

您可以使用ifstreamofstream 如下:

#include <vector> 
#include <algorithm> 
#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    ifstream fin("input.in"); 
    ofstream fout("output.out"); 

    //-- check if the files were opened successfully 
    if (!fin.is_open()) cout << "input.in was not open successfully" << endl; 
    if (!fout.is_open()) cout << "output.out was not open successfully" << endl; 
    int numCase; 
    fin >> numCase; 
    int i, j, n; 
    long long c; 
    for (i = 0; i < numCase; i++) 
    { 
     fin >> n; 
     vector<long long> array1, array2; 
     for (j = 0; j < n; j++) 
     { 
      fin >> c; 
      array1.push_back(c); 
     } 
     for (j = 0; j < n; j++) 
     { 
      fin >> c; 
      array2.push_back(c); 
     } 
     sort(array1.begin(), array1.end()); 
     sort(array2.begin(), array2.end(), greater<long long>()); 
     long long ans = 0; 
     for (j = 0; j < n; j++) 
      ans += (array1[j] * array2[j]); 
     fout << "Case #" << (i + 1) << ": " << ans << endl; 
    } 
    fin.close(); 
    fout.close(); 
    return 0; 
} 

你可以把finfoutcin,所以不是從控制檯讀取輸入,你從文件中讀取in.txt輸入。使用cout來寫信給控制檯,而不是使用fout寫信給output.out

+0

請您能更好地解釋...謝謝 – king 2015-04-03 14:30:32

+0

檢查更新,並注意您將通過上傳output.out文件提交您的答案。 – MrGreen 2015-04-03 14:35:33

+0

因此,這會從in.txt 1中讀取輸入1 ...謝謝。你能幫我把它放在我給你的代碼上面嗎?只是爲了更好的理解 – king 2015-04-03 14:36:37