POJ 1006 數論簡單題

不用中國剩餘定理的知識,直接簡單模擬

#include <iostream>

using namespace std;

const int pc = 23, ep = 28, ip = 33;
int p, e, i, d;

bool Judge(int ans)
{
    if( (ans-p)%pc != 0 )
       return false;
    if( (ans-e)%ep != 0 )
	return false;
    if( (ans-i)%ip != 0 )
	return false;
    return true;
}
int main()
{
    int iCase = 0;
    while( cin >> p >> e >> i >> d && (~p || ~e || ~i || ~d) )
    {
	++iCase;
	p = p%23;
	e = e%28;
	i = i%33;
	int ans = d + 1;
	while( true )
	{
	    if( Judge( ans ) )
	    {
		cout << "Case " << iCase << ": the next triple peak occurs in ";
		cout << ans - d << " days." << endl;
		break;
	    }
	    ++ans;
	}
    }
    return 0;
}
上面的簡單模擬,差一點就超時了,估計在uva上面會超時的,利用中國剩餘定理,o(1)解決戰鬥!

#include <iostream>
#include <cstdio>

using namespace std;

const int PC = 23, EC = 28, IC = 33;
const int PEI = PC*EC*IC;
int n1 = EC*IC, n2 = PC*IC, n3 = PC*EC;

void Init()
{
    int t = n1;
    while( n1%PC != 1 )
	n1 += t;
    t = n2;
    while( n2%EC != 1 )
	n2 += t;
    t = n3;
    while( n3%IC != 1 )
	n3 += t;
}

int main()
{
    int iCase = 0;
    int p, e, i, d;
    Init();
    while( scanf("%d%d%d%d", &p, &e, &i, &d) && (~p || ~e || ~i || ~d) )
    {
	++iCase;
	p %= PC;
	e %= EC;
	i %= IC;
	int ans = (n1*p + n2*e + n3*i)%PEI;
	if( ans <= d )
	    ans += PEI;
	ans -= d;
	cout << "Case " << iCase << ": the next triple peak occurs in ";
	cout << ans << " days." << endl;
    }
}



發佈了76 篇原創文章 · 獲贊 4 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章