zoukankan      html  css  js  c++  java
  • Kattis之旅——Rational Arithmetic

    Input

    The first line of input contains one integer, giving the number of operations to perform.

    Then follow the operations, one per line, each of the form x1 y1 op x2 y2. Here, −109≤x1,y1,x2,y2<109 are integers, indicating that the operands are x1/y1 and x2/y2. The operator op is one of ’+’, ’−’, ’∗’, ’/’, indicating which operation to perform.

    You may assume that y1≠0, y2≠0, and that x2≠0 for division operations.

    Output

    For each operation in each test case, output the result of performing the indicated operation, in shortest terms, in the form indicated.

    Sample Input 1Sample Output 1
    4
    1 3 + 1 2
    1 3 - 1 2
    123 287 / 81 -82
    12 -3 * -1 -1
    
    5 / 6
    -1 / 6
    -82 / 189
    -4 / 1
    

    题目不解释了,看样例也能懂。

    注意用long long。

     //Asimple
    #include <bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    ll n, m, s, res, ans, len, T, k, num;
    ll a, b, c, d;
    char ch;
    
    ll gcd(ll a, ll b ) {
        return b==0?a:gcd(b, a%b);
    }
    
    void print(ll num, ll den){
        bool pos = (num>0 && den>0) || (num<0 && den<0);
        if (num<0) num = -num;
        if (den<0) den = -den;
        ll d = gcd(num,den);
        num /= d , den /= d;
        if (num==0 || den==0) cout << "0 / 1" << endl;
        else cout << (pos?"":"-") << num << " / " << den << endl;
    }
    
    void add_sub(ll x1, ll y1, ll x2, ll y2, int state){
        ll num = x1*y2 + state*x2*y1;
        ll den = y1*y2;
        print(num,den);
    }
    
    void mul(ll x1, ll y1, ll x2, ll y2){
        ll num = x1*x2;
        ll den = y1*y2;
        print(num,den);
    }
    
    void input() {
        cin >> T;
        while( T -- ) {
            cin >> a >> b >> ch >> c >> d;
            switch(ch){
                case '+':
                    add_sub(a, b, c, d,1);
                    break;
                case '-':
                    add_sub(a, b, c, d, -1);
                    break;
                case '*':
                    mul(a, b, c, d);
                    break;
                case '/':
                    mul(a, b, d, c);
                    break;
            }
        }
    }
    
    int main(){
        input();
        return 0;
    }
  • 相关阅读:
    golang学习笔记(7)--函数式编程
    golang学习笔记(6)--面向接口编程
    go语言学习笔记(5)--面向对象
    go语言学习笔记(4)--容器与字符串的基本概念
    go语言学习笔记(3)--简单的程序设计
    go语言学习笔记(2)--go语言语法细节与基本数据类型
    go语言学习笔记(1)--第一个go语言程序
    Linux学习笔记系列(1)
    Scrapy爬虫小demo总结
    python基础总结(6)
  • 原文地址:https://www.cnblogs.com/Asimple/p/6773648.html
Copyright © 2011-2022 走看看