Fun With Fractions |
Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:65536KB |
Total submit users: 152, Accepted users: 32 |
Problem 12878 : No special judgement |
Problem description |
A rational number can be represented as the ratio of two integers, referred to as the numerator (n) and the denominator (d) and written n/d. A rational number's representation is not unique. For example the rational numbers 1/2 and 2/4 are equivalent. A rational number representation is described as "in lowest terms" if the numerator and denominator have no common factors. Thus 1/2 is in lowest terms but 2/4 is not. A rational number can be reduced to lowest terms by dividing by the greatest common divisor of n and d. |
Input |
Input will consist of specifications for a series of tests. Information for |
Output |
Output should consist of one line for each test comprising the test number |
Sample Input |
2 |
Sample Output |
Test 1: 5/6 |
Problem Source |
HNU Contest |
Mean:
给你n个数,其中包含分数、整数,对这n个数求和。
analyse:
按照题目意思模拟即可,主要考察coding能力.
Time complexity:O(n)
Source code:
// K MS
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<iomanip>
#include<string>
#include<climits>
#include<cmath>
#define MAX 1005
#define LL long long
using namespace std;
int n,kase=;
int flag[MAX];
char str[MAX][];
void read()
{
memset(flag,,sizeof(flag));
for(int i=;i<=n;i++)
{
scanf("%s",str[i]);
int len=strlen(str[i]);
for(int j=;j<len;j++)
{
if(str[i][j]==',')
{
flag[i]=;
break;
}
else if(str[i][j]=='/')
{
flag[i]=;
break;
}
}
}
}
int gcd(int a,int b)
{
if(b==)
return a;
else return gcd(b,a%b);
}
int lcm(int a,int b)
{
int x=gcd(a,b);
return a*b/x;
}
void solve()
{
int num;
int zi=,mu=;
for(int i=;i<=n;i++)
{
int a,b;
if(flag[i]==) // 6
{
sscanf(str[i],"%d",&num);
zi+=mu*num;
continue;
}
else if(flag[i]==) // 6,5/3
{
sscanf(str[i],"%d,%d/%d",&num,&a,&b);
zi+=mu*num;
}
else // 5/3
{
sscanf(str[i],"%d/%d",&a,&b);
}
int newmu=lcm(mu,b);
int newa=(newmu/b)*a;
int newzi=(newmu/mu)*zi;
zi=newzi+newa;
mu=newmu;
if(zi%mu==)
{
zi=zi/mu;
mu=;
continue;
}
}
zi-=mu;
if(gcd(zi,mu)!=)
{
int tmp=gcd(zi,mu);
zi/=tmp;
mu/=tmp;
}
if(zi==||mu==)
{
puts("0");
return ;
}
if(zi>=mu)
{
if(zi%mu==)
{
printf("%d\n",zi/mu);
return ;
}
else
{
int integer=;
while(zi>mu)
{
zi-=mu,integer++;
}
printf("%d,%d/%d\n",integer,zi,mu);
return ;
}
}
else
printf("%d/%d\n",zi,mu);
}
int main()
{
// freopen("cin.txt","r",stdin);
// freopen("cout.txt","w",stdout);
while(~scanf("%d",&n),n)
{
read();
printf("Test %d: ",kase++);
solve();
}
return ;
}