acwing368银河/ybtoj恒星的亮度题解

算法:差分约束+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;
}

完结撒花

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值