不用中国剩余定理的知识,直接简单模拟
#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;
}
}