题解:P3530 [POI 2012] FES-Festival
整个题解区好像一个
本篇题解中的强连通分量统一缩写为
首先仍然考虑用差分约束刻画题目中的限制条件。观察到第一种边一定使两个点在同一个
这个时候有一个更加直接的方法:我们对于一个
放代码!(我把限制条件化为
#include<bits/stdc++.h>
using namespace std;
#define rep(i,t1,t2,t3) for(decltype((t1)+(t2)+(t3)) i=(t1);i<=(t2);i+=(t3))
#define pb push_back
#define SZ(x) ((int)(x).size())
template<class T> constexpr bool chkmax(T& a,const T b){return a<b?(a=b,0):1;}
template<class T> constexpr bool chkmin(T& a,const T b){return a>b?(a=b,0):1;}
constexpr int inf=int(1e9)+114514;
void solve(int tid){
int n,m1,m2;cin>>n>>m1>>m2;
vector<vector<pair<int,int>>> edges(n+1);
//差分约束建边
rep(i,1,m1,1){
int u,v;cin>>u>>v;
edges[u].pb({v,1}),edges[v].pb({u,-1});
}
rep(i,1,m2,1){
int u,v;cin>>u>>v;
edges[v].pb({u,0});
}
//Tarjan SCC bel[i]表示i属于哪一个SCC。
vector<int> dfn(n+1),low(n+1),ins(n+1),bel(n+1);
vector<vector<int>> SCC;
stack<int> stk;
int t1=0,t2=0;
//t1是节点标号,t2是SCC标号。
auto TarjanSCC=[&](this auto&& self,int x)->void{
dfn[x]=low[x]=++t1,ins[x]=1,stk.push(x);
for(auto[y,_]:edges[x]){
if(!dfn[y]) self(y),chkmin(low[x],low[y]);
else if(ins[y]) chkmin(low[x],dfn[y]);
}
if(dfn[x]==low[x]){
vector<int> tmp;
t2++;
while(1){
int y=stk.top();stk.pop();
tmp.pb(y),bel[y]=t2,ins[y]=0;
if(x==y) break;
}
SCC.pb(tmp);
}
};
rep(i,1,n,1) if(!dfn[i]) TarjanSCC(i);
//求每个SCC的贡献
auto spfa=[&](int root)->int{
//SPFA最短路
vector<int> dis(n+1,inf),inq(n+1),vis(n+1);
queue<int> q;
dis[root]=0,inq[root]=1,q.push(root);
int limit=SZ(SCC[bel[root]-1]);
while(SZ(q)){
int x=q.front();q.pop();
vis[x]++,inq[x]=0;
//判负环
if(vis[x]>limit){cout<<"NIE\n";exit(0);}
for(auto[y,v]:edges[x])
if(bel[y]==bel[x] && dis[x]+v<dis[y]){
//只计算同一个SCC里的最短路
dis[y]=dis[x]+v;
if(!inq[y]) inq[y]=1,q.push(y);
}
}
//统计最大最小值
int mx=-inf,mn=inf;
for(auto j:SCC[bel[root]-1]){
chkmax(mx,dis[j]),chkmin(mn,dis[j]);
}
return mx-mn+1;
};
int ans=0;
for(auto i:SCC){
int tmp=0;
for(auto root:i) chkmax(tmp,spfa(root));
ans+=tmp;//累计答案
}
cout<<ans<<'\n';
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
int T=1;
// cin>>T;
rep(i,1,T,1) solve(i);
return 0;
}
时间复杂度:最坏情况是全图只有一个