Bzoj2788 [POI2012] Festival

Description

https://www.luogu.com.cn/problem/solution/P3530

Solution

加深了对差分约束的理解。

这种不等式关系考虑建出来差分约束。如果两个点不在一个强连通分量之中,也就是两点之间有且仅有若干条同样的有向路径,此时两者上下限只能确定一个,所以两者实际上只有大小关系。而如果两个点在一个强连通分量,此时两者是有上下限关系的,而在本题中,两者的最短路虽然只表示两者的差值,却也反映了至少经过多少个不同的 $1$ 的边。

不在两个不同的强连通分量一定可以两两不同,因为两者只有大小关系。

所以答案就是在同一个连通块中,两两最短路的最大值 $+1$ 之和。

复杂度 $O(n^3)$。瓶颈在 Floyd。

注意一开始要把 $d_{i,i}=0$。

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
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define maxn 605
#define put() putchar('\n')
#define Tp template<typename T>
#define Ts template<typename T,typename... Ar>
using namespace std;
Tp void read(T &x){
int f=1;x=0;char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();}
x*=f;
}
namespace Debug{
Tp void _debug(char* f,T t){cerr<<f<<'='<<t<<endl;}
Ts void _debug(char* f,T x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);}
#define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__)
}using namespace Debug;
#define fi first
#define se second
#define mk make_pair
const int mod=1e9+7;
int power(int x,int y=mod-2) {
int sum=1;
while (y) {
if (y&1) sum=sum*x%mod;
x=x*x%mod;y>>=1;
}
return sum;
}
int n,m1,m2;
int dis[maxn][maxn],ans[maxn];
int dccnums,dcc[maxn];
int dfn[maxn],low[maxn],stac[maxn],tot,vis[maxn],times;
void tarjan(int x) {
int y;vis[x]=1;dfn[x]=low[x]=++times;stac[++tot]=x;
for (y=1;y<=n;y++) if (dis[x][y]<=1) {
if (!dfn[y]) tarjan(y),low[x]=min(low[x],low[y]);
else if (vis[y]) low[x]=min(low[x],dfn[y]);
}
if (dfn[x]==low[x]) {
++dccnums;
while (tot) {
vis[stac[tot]]=0;
dcc[stac[tot]]=dccnums;
if (stac[tot--]==x) break;
}
}
}
signed main(void){
int i,x,y,j,k;
read(n);read(m1);read(m2);
memset(dis,0x3f,sizeof(dis));
while (m1--) {
read(x);read(y);
dis[x][y]=min(dis[x][y],1);
dis[y][x]=min(dis[y][x],-1);
}
while (m2--) {
read(x);read(y);
dis[y][x]=min(dis[y][x],0);
}
for (i=1;i<=n;i++) dis[i][i]=0;
for (i=1;i<=n;i++) if (!dfn[i]) tarjan(i);
for (k=1;k<=n;k++)
for (i=1;i<=n;i++) if (dcc[i]==dcc[k]) {
for (j=1;j<=n;j++) if (dcc[i]==dcc[j]&&dis[i][j]>dis[i][k]+dis[k][j]) {
dis[i][j]=dis[i][k]+dis[k][j];
}
}
for (i=1;i<=n;i++) if (dis[i][i]<0) return puts("NIE"),0;
for (i=1;i<=n;i++) for (j=1;j<=n;j++) if (dcc[i]==dcc[j]) ans[dcc[i]]=max(ans[dcc[i]],dis[i][j]+1);
int sum=0;
for (i=1;i<=dccnums;i++) sum+=ans[i];
printf("%d\n",sum);
return 0;
}
//i=begin && g++ $i.cpp -o $i -std=c++14 && ./$i