QOJ23675 源点到汇点
Difficulty:Purple。
这题好难喵。我也要场切这种题吗。
显然最开始在环上的点没法被操作,最开始如果存在 GAG 那么就可以一直操作。\
令
因为上面的定义,一条边
::::info[代码]
#include <bits/stdc++.h>
using namespace std;
#define N 100005
#define M 200005
#define inf 1000000008
#define min(A,B) ((A)<(B)?(A):(B))
#define ll long long
ll ans;
int T,n,m,sta[N],top,cnt,dfn[N],low[N],que[N*5],dist[N];
struct ppp{
int to;
bool w;
};
basic_string<ppp>g[N];
basic_string<int>g2[N];
bitset<N>insta,incy,vis;
void Tarjan(const int x){
dfn[x] = low[x] = ++cnt;
sta[++top] = x,insta[x] = 1;
for(int y : g2[x]){
if(insta[y] == 1) low[x] = min(dfn[y],low[x]);
else if(dfn[y] == 0) Tarjan(y),low[x] = min(low[x],low[y]);
}
if(dfn[x] == low[x]){
int j = top-1,y;
while(sta[j+1] != x) --j;
const bool ff = (top - j >= 2);
while(top != j) y = sta[top--],insta[y] = 0,incy[y] = ff;
}
}
void sou(){
int l = (N<<1),r = (N<<1)-1,x,y;
bool z;
for(int i = 1;i <= n;++i) dist[i] = inf;
for(int i = 1;i <= n;++i) if(incy[i] == 1) dist[i] = 0,que[++r] = i;
while(l <= r){
x = que[l++];
if(vis[x] == 1) continue;
vis[x] = 1;
for(ppp qfr : g[x]){
y = qfr.to,z = qfr.w;
if(dist[y] <= dist[x] + z) continue;
dist[y] = dist[x] + z;
if(z == 0) que[--l] = y;
else que[++r] = y;
}
}
ans = 0;
for(int i = 1;i <= n;++i){
if(dist[i] >= inf){ans = -1;return;}
ans += dist[i];
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin >> T;
while(T--){
cin >> n >> m;
for(int i = 1;i <= n;++i) g[i].clear(),g2[i].clear();
for(int i = 1,u,v;i <= m;++i){
cin >> u >> v;
g[u] += (ppp){v,0},g[v] += (ppp){u,1};
g2[u] += v;
}
for(int i = 1;i <= n;++i) dfn[i] = low[i] = 0;
if(n >= 10000) insta.reset(),incy.reset(),vis.reset();
else for(int i = 1;i <= n;++i) insta[i] = 0,incy[i] = 0,vis[i] = 0;
cnt = 0;
for(int i = 1;i <= n;++i){
if(dfn[i] != 0) continue;
Tarjan(i);
}
sou();
cout << ans << '\n';
}
return 0;
}
::::