Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P2662 牛场围栏

P2662 牛场围栏

凑大小类的同余最短路,需要去重减小时间复杂度。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int N = 3e3 + 10, inf = 3e5;
bool vis[N];
int n, m, x, d[N];
vector<int> v;
bool check()
{
if (x == 1)
return true;
for (int i : v)
if (i % x)
return false;
return true;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1, a; i <= n; i++)
{
scanf("%d", &a);
for (int i = max(1, a - m); i <= a; i++)
v.push_back(i);
}
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
x = v.front();
v.erase(v.begin());
if (check())
{
puts("-1");
return 0;
}
for (int i = 1; i < x; i++)
d[i] = inf;
d[0] = 0;
queue<int> q;
q.push(0);
vis[0] = true;
while (!q.empty())
{
int t = q.front();
q.pop();
vis[t] = false;
for (int i : v)
if (d[t] + i < d[(t + i) % x])
{
d[(t + i) % x] = d[t] + i;
if (!vis[(t + i) % x])
{
q.push((t + i) % x);
vis[(t + i) % x] = true;
}
}
}
int res = 0;
for (int i = 1; i < x; i++)
res = max(res, d[i] - x);
printf("%d", res);
return 0;
}