2020年第三场NOI Online入门组
总体难度并不大,但考试时把多重背包忘了,害···
P1830. 最急救助
题目:最急救助
思路:
kmp匹配即可,注意处理好输入和输出,另外本题kmp甚至都不用预处理ne数组,因为p串就是sos,可以知道ne[1]=0,ne[2]=0,ne[3]=1
代码:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 10, M = 220;
char p[N], s[M];
int ne[M];
int n, m, k;
int res;
string ans[110];
int idx;
int main(){
scanf("%d", &k);
p[1] = 's', p[2] = 'o', p[3] = 's';
ne[1] = 0, ne[2] = 0, ne[3] = 1;
n = 3;
while (k -- )
{
int cnt = 0;
string name, word;
cin >> name >> word;
for (int i = 0; i < word.length(); i ++ ) s[i + 1] = word[i];
m = word.length();
//kmp匹配过程
for (int i = 1, j = 0; i <= m; i ++ )
{
while (j && s[i] != p[j + 1]) j = ne[j];
if (s[i] == p[j + 1]) j ++ ;
if (j == n)
{
cnt ++ ;
j=ne[j];
}
}
//分类讨论
if (cnt > res)
{
res = cnt;
idx = 1;
ans[idx] = name;
}
else if (cnt == res)
{
ans[++idx] = name;
}
}
for (int i = 1; i <= idx; i ++ ) cout << ans[i] << " ";
printf("\n");
printf("%d\n", res);
return 0;
}
P1831. 观星
题目:观星
思路:
可以发现本质是找连通块,而floodfill模型恰好就是来找连通块的,star数组类似于桶,star[i]表示星星数量为i的星座有多少个,那么最后这个星系的大小就是i * star[i],直接打擂台即可
代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <set>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 1510, M = N * N, K = 100010;
char g[N][N];
int n, m;
bool st[N][N];
PII q[M];
int star[K]; //桶
int bfs(int sx, int sy) //floodfill
{
int cnt = 1;
int hh = 0, tt = -1;
q[++ tt] = {sx, sy};
st[sx][sy] = true;
while (hh <= tt)
{
PII t = q[hh];
hh ++ ;
for (int i = t.x - 1; i <= t.x + 1; i ++ )
for (int j = t.y - 1; j <= t.y + 1; j ++ )
{
if (i == t.x && j == t.y) continue;
if (i < 0 || i >= n || j < 0 || j >= m) continue;
if (g[i][j] == '.' || st[i][j]) continue;
q[++ tt] = {i, j};
st[i][j] = true;
cnt ++ ;
}
}
return cnt;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
scanf(" %c", &g[i][j]);
set<int> S;
int res = 0;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
{
if (g[i][j] == '*' && !st[i][j])
{
int t = bfs(i, j);
S.insert(t);
star[t] ++ ;
}
}
for (int i = 1; i < K; i ++ )
res = max(res, i * star[i]); //打擂台
printf("%d ", S.size());
printf("%d\n", res);
return 0;
}
P1832. 买表
题目:买表
思路:
类似于P1023.买书,只不过那题是完全背包求方案数,这题是多重背包求方案数,最后如果一块表的方案数为0表示不能凑出,反之则能,由于数据范围过大,朴素做法时间复杂度太大,所以要用二进制优化
代码:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 5e5 + 10;
int v[N];
int f[N];
int n, m, t;
int cnt;
int main()
{
scanf("%d%d", &n, &t);
//二进制优化
for (int i = 1; i <= n; i ++ )
{
int a, s;
scanf("%d%d", &a, &s);
int k = 1;
while (k <= s)
{
v[cnt] = a * k;
s -= k;
k *= 2;
cnt ++ ;
}
if (s > 0)
{
v[cnt] = a * s;
cnt ++ ;
}
}
//多重背包求方案数
n = cnt;
f[0] = 1;
for (int i = 0; i < n; i ++ )
for (int j = 500000; j >= v[i]; j -- )
f[j] += f[j - v[i]];
//依次询问
while (t -- )
{
scanf("%d", &m);
if (!f[m]) puts("No"); //方案数为0
else puts("Yes");
}
return 0;
}