P1314 求多个分数的和
#include <bits/stdc++.h> using namespace std; int gcd(int a,int b) { if(b==0){ return a; }else{ return gcd(b,a%b); } } int main() { string n; getline(cin,n); string a,x,y; int p,q,p1,q1,c; while(n.find('+')>=0 && n.find('+')<n.size()){ c = n.find('+',n.find('+')+1); if(c>=0 && c<n.size()){ a = n.substr(0,c); n = n.substr(c); }else{ a = n; n = ""; } x = a.substr(0,a.find('+')); y = a.substr(a.find('+')+1); p = stoi(x.substr(0,x.find('/'))); p1 = stoi(x.substr(x.find('/')+1)); q = stoi(y.substr(0,y.find('/'))); q1 = stoi(y.substr(y.find('/')+1)); int gcd1 = gcd(max(p1,q1),min(p1,q1)); int lcm = p1*q1/gcd1; p *= lcm/p1; q *= lcm/q1; p1 = lcm; q1 = lcm; p += q; gcd1 = gcd(max(p,p1),min(p,p1)); p /= gcd1; p1 /= gcd1; if(p1!=1){ n = to_string(p)+"/"+to_string(p1)+n; }else{ n = to_string(p)+n; } } cout<<n; return 0; }