p1530 Fractions to Decimals

将余数记录下来,如果余数相同,那么商的下一位也相同。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <cassert>
#include <stack>
#include <bitset>
#define mkp make_pair
using namespace std;
const double EPS=1e-8;
typedef long long lon;
const lon SZ=100030,INF=0x7FFFFFFF,mod=9901;
int vst[SZ];

string work(int n,int d)
{
    if(n==0)return ".0";
    else
    {
        memset(vst,-1,sizeof(vst));
        string str=".";
        int res,rem;
        vst[n]=0;
        for(int i=1;;++i)
        {
            n*=10;
            str+=n/d+'0';
            n=n%d;
            //cout<<i<<" "<<n<<endl;
            if(vst[n]!=-1)
            {
                //cout<<vst[n]<<" "<<i<<endl;
                str=str.substr(0,vst[n]+1)+"("+str.substr(vst[n]+1,i-vst[n])+")";
                break;
            }
            vst[n]=i;
            if(n==0)break;
        }
        return str;
    }
}

string toStr(int x)
{
    if(x==0)return "0";
    string str="";
    for(;x;)
    {
        str=(char)(x%10+'0')+str;
        x/=10;
    }
    return str;
}

int main()
{
    std::ios::sync_with_stdio(0);
    //freopen("d:\\1.txt","r",stdin);
    lon casenum;
    //cin>>casenum;
    //for(lon time=1;time<=casenum;++time)
    {
        int n,d;
        cin>>n>>d;
        string res=toStr(n/d)+work(n%d,d);
        for(int i=0;i<res.size();++i)
        {
            if(i%76==0&&i)cout<<endl;
            cout<<res[i];
        }
        //cout<<res<<endl;
    }
    return 0;
}

 

posted @ 2018-10-22 09:50  degvx  阅读(127)  评论(0编辑  收藏  举报