【发布时间】:2020-08-07 15:23:53
【问题描述】:
我尝试使用动态规划来解决这个问题。 dp[i] 存储在 i 处结束的最长路径。对于从 x 到 y 的每条边,我将 dp[y] 更新为 dp[y] 和 dp[x+1] 之间的最大值。
它适用于输入输出示例,但在判断时某些测试用例失败。还没有想到一个失败的测试用例。任何帮助将不胜感激。
N 是顶点数
M 是边数
x y 表示从 x 到 y 的一条边
输出应该是图中最长路径的长度。
- 样本输入
无名
x1 y1
x2 y2
x3 y3
.
.
.
输入 1
4 5
1 2
1 3
3 2
2 4
3 4
输出 1
3
输入 2
5 8
5 3
2 3
2 4
5 2
5 1
1 4
4 3
1 3
输出 2
3
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,m;
cin>>n>>m;
vector<int> dp(n+1,0);
//dp[i] denotes max length of path ending at node i
int x,y;
for(int i=0;i<m;i++)
{
cin>>x>>y;
dp[y]=max(dp[x]+1,dp[y]);
}
int ans=0;
// for(int i=0;i<n+1;i++)
// cout<<i<< " : "<<dp[i]<<endl;
for(int i=0;i<n+1;i++)
ans=max(ans,dp[i]);
cout<<ans<<endl;
}
【问题讨论】:
-
您好,欢迎来到 stackoverflow。您能否提供工作示例作为测试用例(一些输入产生一些输出,检查是否正确)。因此,帮助您会容易得多。
-
什么是 x 和 y?计算什么?您的问题定义不完整。
-
我添加了更多细节
标签: c++ algorithm graph directed-acyclic-graphs