DAG上的动态规划
上本学期英语的第一节课,老师让做了一套四级题。最后把我的作文拿去看了,最后黯然神伤的走到讲台说了句:“现在我们有请xxx同学产开心扉的,不要在意面子的给我讲讲为什么可以把作文的一句话写的只有一个主语是对的。”深受打击啊!!!!于是决定先不做英语题的题目了,就转回自己的学校OJ了。这就是为什么写这篇博客的原因。
在网上发现了几个学DAG很好的博客,给出链接自己看吧。其中的作者有一些地方是错的,自己注意留言区!!!
Dynamic programming:
(1)problem is solved by identifying a collection of
subproblems,
(2) tackling them one by one, smallest rst,
(3) using the answers of small problems to help
figure out larger ones,
(4) until the whole lot of them is solved.
#include <stdio.h>
#include <string.h>
#define CL(x,v);memset(x,v,sizeof(x));
const int MAX = 1000 + 2;
int n,graph[MAX][MAX],d[MAX];
int DP(int i)
{
if(d[i] > 0) return d[i];
d[i] = 1;
for(int j = 1;j <= n;j++)if(graph[i][j])
d[i] = d[i] > DP(j)+1 ? d[i] : DP(j)+1;
return d[i];
}
int main()
{
int T,i,j,u[MAX],v[MAX];
scanf("%d",&T);
while(T--)
{
CL(graph,0);
CL(d,0);
scanf("%d",&n);
for(i = 1;i <= n;i++)
{
scanf("%d%d",&u[i],&v[i]);
if(u[i] > v[i]){
u[i] += v[i];
v[i] = u[i] - v[i];
u[i] = u[i] - v[i];
}
}
for(i = 1;i <= n;i++)
for(j = 1;j <= n;j++)
if(u[i]<u[j]&&v[i]<v[j])
graph[i][j] = 1;
for(i = 1;i <= n;i++) d[i] = DP(i);
int ans = 0;
for(i = 1;i <= n;i++)
if(ans < d[i]) ans = d[i];
printf("%d\n",ans);
}
return 0;
}