记忆化搜索求DAG最长路

经典问题:嵌套矩形问题
记忆化搜索复杂度和搜索树的边的数目有关(每条边只会使用一次),最坏情况下边数目为n*(n - 1)/2故算法复杂度为O(n^2)

#include<bits/stdc++.h>
#define debug(x) cout<<#x<<" is "<<x<<endl
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define DBG 0
const int N = 1000 + 5;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const ll LLINF = (1LL<<60);
using namespace std;
const int mod = 998244353;
ll fast_pow(ll a,ll b){
	ll ans = 1;
	while(b){
		if(b&1)ans = (ans * a)%mod;
		a = (a * a)%mod;
		b>>=1;
	}
	return (ans%mod);
}
typedef pair<int,int> pii;
int G[N][N],in[N],out[N];
int n;
int ans[N];
struct rect{
	int x,y;
};
vector<rect> v;
int dfs(int i){
	if(ans[i] != -1)return ans[i];
	if(out[i] == 0)return ans[i]  = 
对于一个有向无环图(DAG),可以通过拓扑排序得到其所有可能的拓扑排序。 拓扑排序的步骤如下: 1. 找到入度为0的节点,并将其加入拓扑序列中。 2. 将该节点指向的节点的入度减1。 3. 重复步骤1和2,直到所有节点都被加入拓扑序列中。 如果DAG中存在环,则无法进行拓扑排序。 对于一个DAG,可能存在多种拓扑排序。下面是一个DAG所有可能拓扑排序的算法: 1. 对DAG进行拓扑排序,得到第一种拓扑序列。 2. 将第一种拓扑序列中的每个节点从DAG中删除,得到一个新的DAG。 3. 对新的DAG进行拓扑排序,得到第二种拓扑序列。 4. 将第二种拓扑序列中的每个节点从新的DAG中删除,得到一个新的DAG。 5. 重复步骤3和4,直到得到所有可能的拓扑排序。 下面是一个Python代码实现,用于DAG的所有可能拓扑排序: ```python from collections import defaultdict def all_topological_sorts(graph): in_degree = defaultdict(int) for u in graph: for v in graph[u]: in_degree[v] += 1 q = [u for u in graph if in_degree[u] == 0] result = [] def dfs(path): if len(path) == len(graph): result.append(path) return for u in q: if u not in path: new_path = path + [u] new_q = q.copy() new_q.remove(u) for v in graph[u]: in_degree[v] -= 1 if in_degree[v] == 0: new_q.append(v) dfs(new_path) for v in graph[u]: in_degree[v] += 1 return dfs([]) return result ``` 其中,参数`graph`是一个字典,表示DAG中的节点和边。例如,`graph = {'A': {'B', 'C'}, 'B': {'D'}, 'C': {'D'}, 'D': set()}`表示DAG中有4个节点,分别是A、B、C、D,边的情况如下: ``` A -> B A -> C B -> D C -> D ``` 调用`all_topological_sorts(graph)`函数即可得到DAG的所有可能拓扑排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值