UVA10673---Play With Floor And Ceil

問題描述:

Problem A
Play with Floor and Ceil
Input:
 standard input
Output: standard output
Time Limit: 1 second
 

Theorem

For any two integers x and k there exists two more integers p and q such that:

It’s a fairly easy task to prove this theorem, so we’d not ask you to do that. We’d ask for something even easier! Given the values of x and k, you’d only need to find integers p and q that satisfies the given equation.

 

Input

The first line of the input contains an integer, T (1≤T≤1000) that gives you the number of test cases. In each of the following T lines you’d be given two positive integers x and k. You can safely assume that x and k will always be less than 108.

 

Output

For each of the test cases print two integers: p and q in one line. These two integers are to be separated by a single space. If there are multiple pairs of p and q that satisfy the equation, any one would do. But to help us keep our task simple, please make sure that the values,  and fit in a 64 bit signed integer.

 

Sample Input                              

Output for Sample Input

3

5 2

40 2

24444 6

1 1

1 1

0 6

 



用的是搜索法

#include<iostream>
#include<fstream>
#include<cmath>
#include<cstdlib>
using namespace std;

ifstream fin("C:\\data30.in");

int main()
{
	int T,n,k;
	int f,c;
	int cnt;
	bool beFind;
	fin>>T;
	cnt=0;
	while(cnt<T)
	{
        fin>>n>>k;
        ++cnt;
		f=floor((double)n/k);
		c=ceil((double)n/k);
		beFind=false;
		for(int i=0;i<=k+1;++i)
		{
			for(int j=0;i*f+j*c<=n;++j)
			{
				if(i*f+j*c==n)
				{
					cout<<i<<"\t"<<j<<endl;
					beFind=true;
					break;
				}
			}
			if(beFind)
				break;
		}
	}
	system("pause");
	return 0;
}

找了個答案,用的是數論

//學會使用兩個c語言的函數,floor取下整,ceil取上整
#include <cstdio>
#include <cmath>

void gcd(long long a,long long b,long long& d,long long& x,long long& y)
{
    if(!b) { d=a; x=1; y=0; }
    else   { gcd(b, a%b, d, y, x); y-=x*(a/b); }
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        long long a,b,c,d,k,x,y;
        scanf("%lld%lld",&c,&k);
        a=floor(1.*c/k);  //取下整
        b=ceil(1.*c/k);  //取上整
        gcd(a,b,d,x,y);
        x*=c/d;
        y*=c/d;
        printf("%lld %lld\n",x,y);
    }
    return 0;
}

http://www.cnblogs.com/scau20110726/archive/2013/02/01/2889556.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章