Advertisement
MinhNGUYEN2k4

Untitled

Aug 7th, 2020
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. // cách đệ quy
  2. /*
  3. #include <bits/stdc++.h>
  4. #define int long long
  5. #define MOD 1000000007
  6. using namespace std;
  7. typedef pair<int,int> ii;
  8. typedef vector<ii> viii;
  9. const int N = 100005;
  10.  
  11. int n,m;
  12. viii a[N];
  13. vector<int> f;
  14. int maxx = 0;
  15.  
  16. int calc(int u)
  17. {
  18.     if (f[u] != -1) return f[u];
  19.     f[u] = 0;
  20.     for(int i=0; i<a[u].size(); ++i)
  21.     {
  22.         int v = a[u][i].second;
  23.         f[u] = max(f[u], calc(v) + a[u][i].first) % MOD;
  24.     }
  25. }
  26.  
  27. signed main()
  28. {
  29.     ios_base::sync_with_stdio(false);
  30.     cin.tie(0);cout.tie(0);
  31.     freopen("maxpdag.inp","r",stdin);
  32.     cin >> n >> m;
  33.     f.resize(n+1,-1);
  34.     for(int i=1; i<=m; ++i)
  35.     {
  36.         int u,v,z;
  37.         cin >> u >> v >> z;
  38.         a[u].push_back(ii(z,v));
  39.     }
  40.     for(int i=1; i<=n; ++i)
  41.     {
  42.         f[i] = calc(i);
  43.     }
  44.     for(int i=1; i<=n; ++i)
  45.     {
  46.         //cout << f[i] << endl;
  47.         maxx = max(maxx,f[i]);
  48.     }
  49.     cout << maxx;
  50.     return 0;
  51. }
  52. */
  53.  
  54. // cách topo
  55. #include <bits/stdc++.h>
  56. #define int long long
  57. #define MOD 1000000007
  58. #define TR(k1,k2) for(__typeof((k2).begin()) k1=(k2).begin();k1!=(k2).end();++k1)
  59. using namespace std;
  60. typedef pair<int,int> ii;
  61. typedef vector<ii> vii;
  62. const int N = 100005;
  63.  
  64. int n,m,d[N];
  65. vector<int> b(N,0);
  66. queue<int> q;
  67. vii a[N];
  68.  
  69. void sol()
  70. {
  71.     while (q.size())
  72.     {
  73.         int u = q.front();
  74.         q.pop();
  75.         TR(v,a[u])
  76.         {
  77.             if(d[v->second]<d[u] + v->first) d[v->second]=(d[u]+v->first);
  78.             --b[v->second];
  79.             if (!b[v->second]) q.push(v->second);
  80.         }
  81.     }
  82. }
  83.  
  84. signed main()
  85. {
  86.     ios_base::sync_with_stdio(false);
  87.     cin.tie(0);cout.tie(0);
  88.     freopen("maxpdag.inp","r",stdin);
  89.     int maxx = 0;
  90.     cin >> n >> m;
  91.         int u,v,z;
  92.     for(int i=1; i<=m; ++i)
  93.     {
  94.         cin >> u >> v >> z;
  95.         a[u].push_back(ii(z,v));
  96.         b[v]++;
  97.     }
  98.     for(int i=1; i<=n; ++i) {
  99.             if (!b[i]) q.push(i);
  100.     }
  101.     sol();
  102.     for(int i=1; i<=n; ++i)
  103.     {
  104.         maxx = max(maxx,d[i]);
  105.     }
  106.     cout << maxx;
  107.     return 0;
  108. }
  109.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement