题目链接
动态规划转化成 DAG 然后拓扑求解的思路
虽然很简单不过感觉这个新思路会很有用!
如果两个事件互不影响并且有先后关系,就可以连一条有向边,跑最长路可以得到最后的最优解
实际上这还是个背包……
#include <queue>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std; const int maxn = + ;
int n, m, r, head[maxn], dis[maxn], in_deg[maxn], edge_num, ans; struct Segment {
int lef, rig, enr;
inline bool operator < (const Segment &x) const{ return this->rig < x.rig; }
} seg[maxn]; struct Edge { int v, nxt; } edge[maxn * maxn]; inline int read() {
register char ch = ; register int w = , x = ;
while( !isdigit(ch) ) w |= (ch == '-'),ch = getchar();
while( isdigit(ch) ) x = (x * ) + (ch ^ ), ch = getchar();
return w ? -x : x;
} inline void Add_edge(int u, int v) {
edge[++edge_num].v = v;
edge[edge_num].nxt = head[u], head[u] = edge_num;
} inline void Breath_fs() {
queue<int> q;
for(int i = ; i <= m; ++i) dis[i] = seg[i].enr;
for(int i = ; i <= m; ++i) if( !in_deg[i] ) q.push(i);
while( !q.empty() ) {
int x = q.front(); q.pop();
for(int i = head[x]; i; i = edge[i].nxt) {
if( dis[edge[i].v] < dis[x] + seg[edge[i].v].enr )
dis[edge[i].v] = dis[x] + seg[edge[i].v].enr;
if( --in_deg[edge[i].v] == ) q.push(edge[i].v);
}
}
} int main(int argc, char const *argv[])
{
freopen("nanjolno.in", "r", stdin);
freopen("nanjolno.out", "w", stdout); scanf("%d%d%d", &n, &m, &r);
for(int i = ; i <= m; ++i)
seg[i].lef = read(), seg[i].rig = read() + r, seg[i].enr = read();
sort(seg + , seg + m + ), ans = ;
for(int i = ; i <= m; ++i) for(int j = i + ; j <= m; ++j)
if( seg[i].rig <= seg[j].lef ) Add_edge(i, j), ++in_deg[j];
Breath_fs();
for(int i = ; i <= m; ++i) ans = max(ans, dis[i]);
printf("%d\n", ans); fclose(stdin), fclose(stdout);
return ;
}
—— 冬天来了 —— 那是悲喜交加,永远的瞬间。