AcWing 197. 阶乘分解
https://www.acwing.com/problem/content/199/
思路:暴力会t!首先肯定是要先筛质数,之后我们会发现,所有小于n的质数p,因为每个p的倍数里都有一个p,那么每个倍数里都至少有一个p,所以先出现了n / p次;但是对于每一个p^2的倍数,我们少算了一个p,再加上n / (p2)次,再考虑p3的倍数,以此类推。
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 10;
int p[maxn], idx, n;
bool st[maxn];
void init()
{
for(int i = 2;i <= n; i++)
{
if(!st[i]) p[++idx] = i;
for(int j = 1;p[j] <= n / i; j++)
{
st[p[j] * i] = true;
if(i % p[j] == 0) break;
}
}
}
int main()
{
cin >> n;
init();
for(int i = 1;p[i] <= n && i <= idx; i++)
{
ll t = p[i];
ll ans = 0;
while(t <= n)
{
ans += n / t;
t *= p[i];
}
cout << p[i] << ' ' << ans << endl;
}
return 0;
}
AcWing 1129. 热浪
https://www.acwing.com/problem/content/1131/
思路:SPFA最短路跑一遍。
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 2510;
const int maxm = 6200 * 2 + 10;
int h[maxn], e[maxm], ne[maxm], w[maxm], idx;
int S, E, n, m;
int dist[maxn];
bool st[maxn];
void add(int x, int y, int z)
{
w[idx] = z;
e[idx] = y;
ne[idx] = h[x];
h[x] = idx++;
}
void spfa()
{
memset(dist, 0x3f, sizeof(dist));
queue<int> q;
dist[S] = 0;
q.push(S);
st[S] = true;
while(q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for(int i = h[t];i != -1;i = ne[i])
{
int j = e[i];
if(dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if(!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
}
int main()
{
scanf("%d%d%d%d", &n, &m, &S, &E);
memset(h, -1, sizeof(h));
while(m--)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
add(b, a, c);
}
spfa();
printf("%d\n", dist[E]);
return 0;
}
AcWing 173. 矩阵距离
https://www.acwing.com/problem/content/175/
思路:多源BFS。
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 1010;
typedef struct
{
int x, y;
}P;
int n, m;
char a[maxn][maxn];
int ans[maxn][maxn];
bool st[maxn][maxn];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int main()
{
scanf("%d%d", &n, &m);
for(int i = 1;i <= n; i++)
scanf("%s", a[i] + 1);
queue<P> q;
for(int i = 1;i <= n; i++)
{
for(int j = 1;j <= m; j++)
{
if(a[i][j] == '1')
{
st[i][j] = true;
q.push({i, j});
ans[i][j] = 0;
}
}
}
while(q.size())
{
P t = q.front();
q.pop();
for(int i = 0;i < 4; i++)
{
int x = t.x + dx[i];
int y = t.y + dy[i];
if(x >= 1 && x <= n && y >= 1 && y <= m && !st[x][y])
{
st[x][y] = true;
q.push({x, y});
ans[x][y] = ans[t.x][t.y] + 1;
}
}
}
for(int i = 1;i <= n; i++)
{
for(int j = 1;j <= m; j++)
{
printf("%d ", ans[i][j]);
}
printf("\n");
}
return 0;
}