UVA - 10976 Fractions Again?! C++

题目:https://odzkskevi.qnssl.com/27d81f981b3aae8419cb258315756d15?v=1532307350

思路:

就是暴力地遍历……然后我是把每一对x和y存在队列里,最后读出。

因为1/n=1/x+1/y,1/y>0,所以1/n>1/x,即n<x。所以遍历的时候只要从n+1开始就好了。又因为x>=y,所以1/n<2/x,即x<2n。

代码:

#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
queue<pair<int,int> >q;
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        int tot=0;
        int x,y;
        for(int i=n+1;i<=2*n;i++)
        {
            y=i;
            if((n*y)%(y-n)==0)
            {
                x=(n*y)/(y-n);
                q.push(pair<int,int>(x,y));
                tot++;
            }
        }
        cout<<tot<<endl;
        while(!q.empty())
        {
            pair<int,int> p=q.front();
            q.pop();
            int nx=p.first,ny=p.second;
            printf("1/%d = 1/%d + 1/%d\n",n,nx,ny);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zero_979/article/details/81172686