1、fact4
這個問題在《編程之美》上有過一個類似的問題,大概是求階乘 n! 後面有多少個0,最後可以轉換爲求[1,N]之間因子5有多少次。這個問題和fact4有點淵源,對於 n! 的尾數,看看規律就知道了:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5,040
8! = 40,320
9! = 362,880
10! = 3,628,800
11! = 39,916,800
12! = 479,001,600
13! = 6,227,020,800
14! = 87,178,291,200
15! = 1,307,674,368,000
16! = 20,922,789,888,000
其實都是有 (n-1)! 的非0尾數與 n 乘積的尾數,唯一的麻煩是遇到了5,就會使得尾數變0,這時候要往進位去找新產生的尾數。好了,所有的 Trick 都在這了。我們看到題目指出 n 不大於4220 < 5^6,所以,代碼如下,注意那個pow:
-
#include <fstream>
-
using namespace std;
-
-
ifstream fin("fact4.in");
-
ofstream fout("fact4.out");
-
-
int N;
-
-
int main()
-
{
-
fin >> N;
-
-
int multiplier = 1, pow = 100000, factor;
-
for(int i = 1; i <= N; ++i)
-
{
-
factor = i % pow;
-
multiplier = multiplier * factor;
-
-
while(multiplier % 10 == 0)
-
multiplier /= 10;
-
-
while(multiplier / pow > 0)
-
multiplier %= pow;
-
}
-
-
fout << multiplier % 10 << endl;
-
-
return 0;
-
}
2、spin
單純樸素模擬,藉助STL的bitset來存儲輪子們的位置信息,因爲數據量實在是小,所以沒必要用線段樹來做時空優化了,要是用線段樹,肯定要快N倍吧。然後其實你不用bitset,直接開一個bool數組也是OK的。
-
#include <fstream>
-
#include <bitset>
-
using namespace std;
-
ifstream fin("spin.in");
-
ofstream fout("spin.out");
-
-
#define PI 360
-
int speed[6];
-
bitset<PI> curr[6], next[6];
-
-
int main()
-
{
-
int num, start, end;
-
for(int i=1; i<=5; i++)
-
{
-
fin >> speed[i] >> num;
-
for(int j = 1; j <= num; j++)
-
{
-
fin >> start >> end;
-
end += start;
-
for(int k = start; k <= end; k++)
-
curr[i].set(k%PI);
-
}
-
}
-
-
int angle = 0;
-
bool flag;
-
while(angle < PI)
-
{
-
for(int i = 0; i < PI; ++i)
-
{
-
flag = false;
-
for(int j = 1; j <= 5; j++)
-
{
-
if(!curr[j].test(i))
-
{
-
flag = true;
-
break;
-
}
-
}
-
if(!flag)
-
{
-
fout << angle << endl;
-
return 0;
-
}
-
}
-
-
for(int i = 1; i <= 5; i++)
-
{
-
for(int j = 0; j < PI; j++)
-
next[i][j] = curr[i][(j+PI-speed[i])%PI];
-
curr[i]=next[i];
-
}
-
-
++angle;
-
}
-
-
fout << "none" << endl;
-
return 0;
-
}