輸入輸出細節處理,USACO Fractions to Decimals

算法還是很簡單的,基本上學過小學除法算術的都知道,n/d的每位運算所得的餘數只可能是0..d-1,如果在某處出現一個餘數之前曾經出現過(在小數位上),那麼可以肯定此時從該處到上次用出現這個這個商之間存在循環節。這樣,就可以用基本的標記法就可以了。

所以這題其實麻煩的是輸出的處理,又要加括號,又要求每行只能輸出76個字符。麻煩!害得我又WA了兩次,鬱悶中。



/*
ID: fairyroad
TASK: fracdec
LANG: C++
*/
#include<fstream>
#include<vector>
using namespace std;
ifstream fin("fracdec.in");
ofstream fout("fracdec.out");

bool existed[100001];
size_t index[100001];
vector<int> remainder;

inline size_t countp(int num)
{
    if(!num) return 1;
    int res = 0;
    while(num) ++res, num/=10;
    return res;
}

int main()
{
    int n, d;
    fin>>n>>d;
    int f = 0, cnt = 0;
    bool flag = true; // 是否能整除,與加括號有關
    if(n >= d){ f = n/d; n = n%d; }
    while(!existed[n])
    {
        existed[n] = true;
        index[n] = cnt++;
        remainder.push_back(n*10/d);
        if((n*10)%d==0){flag = false;break;}
        n = (n*10)%d;
    }

    fout<<f<<'.';
    size_t charnum = countp(f)+1;
    for(size_t i = 0; i < remainder.size(); ++i)
    {
        if(charnum == 76) fout<<endl, charnum = 0;
        if(i == index[n] && flag)  ++charnum, fout<<'(';
        fout<<remainder[i];
        ++charnum;
    }
    if(flag) fout<<')';
    fout<<endl;

    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章