POJ 3249 Test for Job 拓撲排序+DP

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   資料   for   問題   

http://poj.org/problem?id=3249

題意:

給一個有向非循環圖DAG(不一定聯通),每個點有權值,入度為0的點為起點,出度為0的點為終點,選擇一個起點走到一個終點,使得路上的權和最大。

分析:

dp[to] = max(dp[from]) + value[to],然後先拓撲排序保證狀態正確轉移即可,終點做標記,如果是終點則嘗試更新答案。

update:因為點權可以為負,所以程式裡用dp[i] == -1表示未訪問過該點是有問題的,不過沒有遇上會卡掉這種情況的資料=。=

 

 1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<queue> 5 using namespace std; 6  7 int n, m, esize, x, y; 8 int a[100100], en[100100], in[100100], bfn[100100], dp[100100]; 9 bool ed[100100];10 struct edge{11     int v, n;12 } e[1000100];13 void addedge(int u, int v)14 {15     e[esize].v = v;;16     e[esize].n = en[u];17     en[u] = esize ++;18 }19 queue<int> q;20 int main()21 {22     while(scanf("%d%d", &n, &m) != EOF)23     {24         for (int i = 1; i <= n; i++)25             scanf("%d", a+i);26         memset(en, -1, sizeof(en));27         memset(in, 0, sizeof(0));28         memset(ed, true, sizeof(ed));29         esize = 0;30         for (int i = 0; i < m; i++){31             scanf("%d %d", &x, &y);32             addedge(x, y);33             in[y]++;34             ed[x] = 0;35         }36         for (int i = 1; i <= n; i++)37             if (!in[i]) q.push(i);38         int ans = -2147483640;39         int cnt = 0;40         while(!q.empty())41         {42             int u = q.front(); q.pop();43             bfn[cnt++] = u;44             for (int t = en[u]; t != -1; t = e[t].n){45                 int v = e[t].v;46                 in[v] --;47                 if (in[v] == 0)    q.push(v);48             }49         }50         memset(dp, -1, sizeof(dp));51         for (int i = 0; i < n; i++){52             int u = bfn[i];53             if (dp[u] == -1) dp[u] = a[u];54             if (ed[u]) ans = max(ans, dp[u]);55             for (int t = en[u]; t != -1; t = e[t].n){56                 int v = e[t].v;57                 if (dp[v] == -1 || dp[v] < dp[u] + a[v])58                     dp[v] = dp[u] + a[v];59             }60         }61         printf("%d\n", ans);62     }63     return 0;64 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.