算法:差分约束+trajan+拓扑dp;
思路,根据关系,建立连向:
cin>>x>>y>>z;
if(z==1){
e1[x].push_back({y,0}),e1[y].push_back({x,0});
}else if(z==2){
e1[x].push_back({y,1});
}else if(z==3){
e1[y].push_back({x,0});
}else if(z==4){
e1[y].push_back({x,1});
}else e1[x].push_back({y,0});
大于关系建1边,小于关系建2边:
当x,y强连通,x,y一定相等,即为col[x]=col[y],否则不合法,输出-1;
求出f数组的最小值;
时间复杂度: O(n+m);
code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N=1e5+10;
typedef pair<int,int>PII;
int que[N],dfn[N],low[N],ru[N],stak[N],col[N],qr,n,m,top,tot=0,time1;
vector<PII>e1[N],e2[N];
typedef long long LL;
LL ans=0;
int f[N],num[N];
inline void trajan(int x){
low[x]=dfn[x]=++time1;
stak[++top]=x;
for(PII v:e1[x]){
int y=v.first;
if(!dfn[y]){
trajan(y);
low[x]=min(low[x],low[y]);
}else if(!col[y]){
low[x]=min(low[x],dfn[y]);
}
}
if(dfn[x]==low[x]){
col[x]=++tot;
num[tot]=1;
int y;
while(y=stak[top--],y!=x){
col[y]=tot,num[tot]++;
}
}
}
int main(){
cin>>n>>m;
for(int i=1,x,y,z;i<=m;i++){
cin>>z>>x>>y;
if(z==1){
e1[x].push_back({y,0}),e1[y].push_back({x,0});
}else if(z==2){
e1[x].push_back({y,1});
}else if(z==3){
e1[y].push_back({x,0});
}else if(z==4){
e1[y].push_back({x,1});
}else e1[x].push_back({y,0});
}
for(int i=1;i<=n;i++){
if(!dfn[i]){
trajan(i);
}
}
for(int x=1;x<=n;x++){
for(PII y:e1[x]){
int v=y.first,w=y.second;
if(col[x]==col[v]&&w==1){
cout<<-1<<endl;
return 0;
}else if(col[x]!=col[v]){
e2[col[x]].push_back({col[v],w});
++ru[col[v]];
}
}
}
for(int x=1;x<=tot;x++){
if(!ru[x]){
que[++qr]=x,f[x]=1;
}
}
for(int i=1;i<=qr;i++){
int x=que[i];
for(PII y:e2[x]){
int v=y.first,w=y.second;
f[v]=max(f[v],f[x]+w);
if(!--ru[v]) que[++qr]=v;
}
}
for(int x=1;x<=tot;x++){
ans+=f[x]*num[x];
}
cout<<ans<<endl;
return 0;
}
完结撒花