Blog of RuSun

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

P3275 [SCOI2011]糖果

P3275 [SCOI2011]糖果

正解是 tarjan ,这里做的是差分约束,复杂度差一些,需要玄学卡过。

正解:先做操作 $1$ 、$3$ 、$5$ ,缩点,建新图,一个强连通分量上的点值一定是一样的。再做操作 $2$ 、$4$ ,如果是自环,直接无解。再做拓扑排序,如果还有环,则无解。拓扑排序后,统计答案即可。

差分约束做法:直接做,将 spfa 中的 queue 改为 stack 玄学卡过。

查看代码
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <climits>
#define INF INT_MAX
using namespace std;
const int N = 1e5 + 10, M = 3e5 + 10;
bool vis[N];
int n, m, st, d[N], cnt[N];
int idx = -1, hd[N], nxt[M], edg[M], wt[M];
bool spfa()
{
for (int i = 0; i <= n; i++)
d[i] = -INF;
d[st] = 0;
stack <int> q;
q.push(st);
vis[st] = true;
while (!q.empty())
{
int t = q.top();
q.pop();
vis[t] = false;
for (int i = hd[t]; ~i; i = nxt[i])
if (d[t] + wt[i] > d[edg[i]])
{
d[edg[i]] = d[t] + wt[i];
cnt[edg[i]] = cnt[t] + 1;
if (cnt[t] > n)
return false;
if (!vis[edg[i]])
{
q.push(edg[i]);
vis[edg[i]] = true;
}
}
}
return true;
}
void add(int a, int b, int c)
{
nxt[++idx] = hd[a];
hd[a] = idx;
edg[idx] = b;
wt[idx] = c;
}
int main()
{
cin >> n >> m;
st = 0;
for (int i = 0; i <= n; i++)
hd[i] = -1;
for (int i = 1; i <= n; i++)
add(st, i, 1);
for (int i = 1, x, a, b; i <= m; i++)
{
cin >> x >> a >> b;
if (x == 1)
{
add(a, b, 0);
add(b, a, 0);
}
else if (x == 2)
add(a, b, 1);
else if (x == 3)
add(b, a, 0);
else if (x == 4)
add(b, a, 1);
else if (x == 5)
add(a, b, 0);
}
if (!spfa())
{
cout << "-1";
return 0;
}
long long tot = 0;
for (int i = 1; i <= n; i++)
tot += d[i];
cout << tot;
return 0;
}