Codeforces Round #660 (Div. 2) D (拓扑排序,递归写法)

https://codeforces.com/contest/1388/problem/D
在这里插入图片描述

思路

使用拓扑排序,递归写的拓扑排序速度和空间开销较大,时间大约2倍,空间6倍多,有风险,但是代码简单,可以借鉴。故意卡数据的不存在。

代码

// 递归代码
#include<bits/stdc++.h>
#define ios std::ios::sync_with_stdio(false) , std::cin.tie(0) , std::cout.tie(0)
#define rep(i,a,n) for (int i=a;i<=n;i++)
#define per(i,n,a) for (int i=n;i>=a;i--)
#define ll long long
#define pb push_back
using namespace std;
const int N = 2e5 + 10;
int b[N],vis[N];
vector<int> vec,G1[N],G2[N];
ll ans,a[N];
void solve(int u,int s){
	if (s == 1){//入度=0 
		if (a[u] >= 0){
			ans += a[u], vis[u] = 1, vec.pb(u);
			for (auto it:G1[u]) a[it] += a[u], solve(it,2);
		}
		else{
			vis[u] = 1; 
			for (auto it:G1[u]) solve(it,2);
			ans += a[u], vec.pb(u);
		}
	}
	else{		
		int flag = 1;
		for (auto it:G2[u]) 
			if (!vis[it]) flag = 0, solve(it,2); //入度>0 
		if (flag) solve(u,1); //入度=0
	}
}
int main()
{
	int n;
	cin >> n;
	rep(i,1,n) cin >> a[i];
	rep(i,1,n){
		cin >> b[i];
		if (b[i] == -1) continue;
		G1[i].pb(b[i]);// 出 
		G2[b[i]].pb(i);// 入 
	}
	rep(i,1,n){
		int len = G2[i].size();
		if (!vis[i] && !len) solve(i,2); //入度=0
	}
	cout << ans << "\n";
	for (auto it:vec) cout << it << " ";
    return 0;
}
// 常规代码
#include<bits/stdc++.h>
#define ios std::ios::sync_with_stdio(false) , std::cin.tie(0) , std::cout.tie(0)
#define rep(i,a,n) for (int i=a;i<=n;i++)
#define per(i,n,a) for (int i=n;i>=a;i--)
#define ll long long
#define pb push_back
using namespace std;
const int N = 2e5 + 10;
int b[N],indu[N],res[N],cnt;
ll a[N],ans;
int main()
{
	int n;
	cin >> n;
	rep(i,1,n) cin >> a[i];
	rep(i,1,n){
		cin >> b[i];
		if (b[i] != -1){
			indu[b[i]]++;
		}
	}
	queue<int> q;
	stack<int> s;
	rep(i,1,n){
		if (!indu[i]) q.push(i);
	}
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		ans += a[u];
		if (a[u] < 0){
			s.push(u);
			indu[b[u]]--;
			if (!indu[b[u]]) q.push(b[u]);
			continue;
		}
		else if (b[u] != -1){
			a[b[u]] += a[u];
			indu[b[u]]--;
			if (!indu[b[u]]) q.push(b[u]);
		}
		res[++cnt] = u;
	}
	cout << ans << "\n";
	rep(i,1,cnt) cout << res[i] << " ";
	while(!s.empty()){
		cout << s.top() << " ";
		s.pop();
	}
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值