QOJ23675. Source to Sink
:::::success[Hint 1]
钦定
对应 Hint 1:
钦定
我们考虑手玩样例和小数据,我们观察到答案为
我们考虑证明 DAG 操作之后仍然是 DAG,考虑反证法,假设 DAG
所以 DAG 操作后还是 DAG,证毕。
对应 Hint 2:
设
对于任意一条边
同时,我们必须要求在非单点强连通分量之内的点
考虑证明上面这一点,考虑通过构造证明。
我们考虑归纳证明,考虑对
那么这样我们对于每条边
这样我们就做完了这道题。
时空复杂度均为
:::::success[code]
#include<bits/stdc++.h>
#define inl inline
#define int long long
#define lll __int128
#define fst ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define rep(i,x,y) for(int i=x;i<=(y);++i)
#define per(i,x,y) for(int i=x;i>=(y);--i)
#define rpr(i,x,y,z) for(int i=x;i<=(y);i+=z)
#define epe(i,x,y,z) for(int i=x;i>=(y);i-=z)
#define repe(i,x,y) for(i=x;i<=(y);++i)
#define endl '\n'
#define INF 1e16
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define fi first
#define se second
#define lcm(x,y) x/__gcd(x,y)*y
#define ull unsigned long long
#define prr make_pair
#define pii pair<int,int>
#define gt(s) getline(cin,s)
#define at(x,y) for(const auto &x:y)
#define ff fflush(stdout)
#define mt(x,y) memset(x,y,sizeof(x))
#define idg isdigit
#define fp(s) string ssss=s;freopen((ssss+".in").c_str(),"r",stdin);freopen((ssss+\
".out").c_str(),"w",stdout);
#define sstr stringstream
#define all(x) x.begin(),x.end()
#define mcy(a,b) memcpy(a,b,sizeof(b))
#define ui unsigned
#define si signed
#define eb emplace_back
#define pff(x) ((x)*(x))
#define eush emplace
#define double long double
#define pdi pair<double,int>
#ifdef __unix__
#define gc getchar_unlocked
#else
#define gc _getchar_nolock
#endif
#ifdef __unix__
#define pc putchar_unlocked
#else
#define pc _putchar_nolock
#endif
using namespace std;
const int N=1e5+5;
vector<int>g[N];
struct edges{
int v,w;
inl edges(){
v=w=0;
}
inl edges(int v,int w):v(v),w(w){}
};
vector<edges>gx[N];
int dfn[N],low[N],cnt,col[N],color,sum[N],f[N];
bool vis[N];
stack<int>st;
inl void tarjan(int u){
dfn[u]=low[u]=++cnt;
vis[u]=1;
st.push(u);
at(v,g[u])
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}else if(vis[v]) low[u]=min(low[u],low[v]);
if(dfn[u]==low[u]){
++color;
while(!st.empty()){
int v=st.top();
col[v]=color;
++sum[color];
st.pop();
vis[v]=0;
if(u==v) break;
}
}
}
inl void solve(){
int n,m,ans=0;
cin>>n>>m;
rep(i,0,n+1) g[i].clear();
rep(i,0,n+1) gx[i].clear();
while(!st.empty()) st.pop();
rep(i,0,n+1) dfn[i]=low[i]=col[i]=sum[i]=vis[i]=0;
color=cnt=0;
rep(i,0,n+1) f[i]=INF;
rep(i,1,m){
int u,v;
cin>>u>>v;
g[u].pb(v);
gx[u].eb(v,0);
gx[v].eb(u,1);
}
rep(i,1,n)
if(!dfn[i]) tarjan(i);
rep(i,0,n+1) vis[i]=0;
deque<int>dq;
rep(i,1,n)
if(sum[col[i]]>1){
dq.pb(i);
f[i]=0;
}
while(!dq.empty()){
int u=dq.front();
dq.pof();
if(vis[u]) continue;
vis[u]=1;
at(x,gx[u]){
int v=x.v,w=x.w;
if(f[v]>f[u]+w){
f[v]=f[u]+w;
if(!w) dq.pf(v);
else dq.pb(v);
}
}
}
rep(i,1,n)
if(f[i]==INF){
cout<<-1<<endl;
return;
}
rep(i,1,n) ans+=f[i];
cout<<ans<<endl;
}
si main(){
fst;
int t;
cin>>t;
while(t--) solve();
return 0;
}
:::::