USACO Section 2.4: Fractions to Decimals

乍看题目感觉有难度,实际分析后其实是道简单题

 1 /*

 2 ID: yingzho1

 3 LANG: C++

 4 TASK: fracdec

 5 */

 6 #include <iostream>

 7 #include <fstream>

 8 #include <string>

 9 #include <map>

10 #include <vector>

11 #include <set>

12 #include <algorithm>

13 #include <stdio.h>

14 #include <queue>

15 #include <cstring>

16 #include <cmath>

17 #include <list>

18 

19 using namespace std;

20 #define inf 10000000

21 

22 ifstream fin("fracdec.in");

23 ofstream fout("fracdec.out");

24 

25 int N, D;

26 vector<int> rec;

27 set<int> recset;

28 

29 int GCD(int a, int b)

30 {

31    if (b==0) return a;

32    return GCD(b,a%b);

33 }

34 

35 string intToString(int n) {

36     string ret;

37     if (n == 0) return "0";

38     while (n) {

39         char tmp = char('0' + n%10);

40         ret += tmp;

41         n /= 10;

42     }

43     reverse(ret.begin(), ret.end());

44     return ret;

45 }

46 

47 int main()

48 {

49     fin >> N >> D;

50     int gcd = GCD(N, D);

51     N /= gcd, D/= gcd;

52     if (D == 1) {

53         fout << N << ".0" << endl;

54         return 0;

55     }

56     int first = N / D;

57     int second = N % D;

58     string res;

59     int againindex = 0;

60     while (second != 0) {

61         if (recset.count(second*10)) {

62             for (; againindex < rec.size(); againindex++) {

63         //        cout << rec[againindex] << endl;

64                 if (rec[againindex] == second*10) {

65                     againindex++;

66                     break;

67                 }

68             }

69             break;

70         }

71         res = res + char('0'+second*10/D);

72         rec.push_back(second*10);

73         recset.insert(second*10);

74       //  cout << "second: " << second << endl;

75         second = second * 10 % D;

76     }

77     //cout << res << endl;

78     //cout << againindex << endl;

79     if (againindex) {

80         res.insert(againindex-1, "(");

81         //cout << res << endl;

82         res += ")";

83     }

84     string ret = intToString(first) + "." + res;

85     //cout << ret;

86     for (int i = 0; i < ret.size(); i++) {

87         fout << ret[i];

88         if (i % 76 == 75 && i > 0) fout << endl;

89     }

90     if (ret.size() % 76 != 75) fout << endl;

91     //if (first > 0) fout << first << "." << res << endl;

92     //else fout << "0." << res << endl;

93 

94     return 0;

95 }

 

你可能感兴趣的:(action)