【UVA10976】Fractions Again?!(结构体内重载运算符---水题)

版权声明:转载请注明出处哦~ https://blog.csdn.net/Cassie_zkq/article/details/87832540

题目:https://vjudge.net/problem/UVA-10976

解题思路:


对式子变形,可以得出:k=(xy)/(x+y)

当x=y时x=y=2k;

当y=2k时,若x>y则不会出现题目中的等式,k<(xy)/(x+y)

可知y的最大值为2k,最小值刚开始我是按从1开始运行程序的,但是有错误,后来意识到在用y求x的值时

x=ky/(y-k),为了保证x是正整数,y(min)=k+1;

除法分母不能为0!!y从1开始时会出现分母为0的情况,所以未输出后面的结果程序就已经中断了!

结构体内重载<运算符

刚开始的写法会报错:

解决方法是在bool前面加friend ,加完friend之后可以玩把const 和引用去掉

ac代码:


#include <iostream>
#include <cmath>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <stdlib.h>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <sstream>
using namespace std;
typedef long long ll;
struct pa{
    ll x,y;
    pa(ll x=0,ll y=0):x(x),y(y){}
    friend bool operator <(pa a,pa b)
    {
        return a.x==b.x?a.y>b.y:a.x>b.x;
    }
};
int main()
{
    ll k;
    //freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
    while(scanf("%lld",&k)!=EOF)
    {
        set<pa> ans;
        ll num=0,x,y;
        for(y=k+1;y<=2*k;y++)
        {
            x=k*y/(y-k);
            //cout<<x<<endl;
            if(x*(y-k)==k*y &&x>=y &&x>0)
            {
                num++;
                ans.insert(pa(x,y));
            }
        }
        printf("%lld\n",num);
        for(set<pa>::iterator it=ans.begin();it!=ans.end();it++)
            printf("1/%lld = 1/%lld + 1/%lld\n",k,it->x,it->y);


    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cassie_zkq/article/details/87832540
今日推荐