演算法:uva 1484 Alice and Bob's Trip (樹形dp)

來源:互聯網
上載者:User

題意

給一棵n個結點的樹,結點編號為0~n-1,頂點是0

每條邊都有一個權值。

Alice和Bob初始位 置在頂點,要往下一直走到葉子結點。

第一次是由Bob選擇走向哪個子結點,第二次輪到Alice,依次輪流 下去...

每走過一條邊就會獲得相應的權值,Bob希望所走的路徑總權值越大越好,而Alice希望越小越好

每次他們都會選擇最優解。

最終總權值要在範圍[L,R]之內。

問最終Bob希望的最大權值是多少?

思路

f(u, 0)表示第u點由Bob選時的最大值

f(u, 1)表示第u點由Alice選時的最大值

tot(u) 表示由頂點走到i點的權值之和

w(u,v)表示連接點u和v的邊的權值

那麼

f (u, 0) = max{ f(v, 1) + w(u,v) | v是u的兒子結點 && L <= f(v,1)+w(u)+tot(u) <= R}

f(u, 1) = min{ f(v, 0) + w(u,v) | v是u的兒子結點 && L <= f(v,0)+w(u)+tot(u) <= R}

最終答案為f(0, 0)

另外,這題在HDU題提交時,用C++可以AC,但是用G++卻TLE了,不知為 什麼。

而在uva和LA提交,是SubmissionErr,然後問UVA管理員,說是系統問題暫時無法解 決...

代碼

/**==========================================* This is a solution for ACM/ICPC problem** @source:uva-1484 Alice and Bob's Trip* @type: 樹形dp* @author: shuangde* @blog: blog.csdn.net/shuangde800* @email: zengshuangde@gmail.com*===========================================*/   #include<iostream>#include<cstdio>#include<algorithm>#include<vector>#include<queue>#include<cmath>#include<cstring>   typedef long long int64;   const int INF = 0x3f3f3f3f;const double PI = acos(-1.0);const int MAXN = 500010;   namespace Adj{int head[MAXN];int size;   struct Node{int v, w, next;}E[MAXN];   inline void initAdj() {size = 0;memset(head, -1, sizeof(head));}   inline void addEdge(int u, int v, int w) {E[size].v = v;E[size].w = w;E[size].next = head[u];head[u] = size++;}}   using namespace Adj;using namespace std;   int n, l, r;int f[MAXN][2];int dist[MAXN];   inline bool check(int sum) {return sum >=l && sum <= r;}   void dfs(int u, int tot) {f[u][0] = 0;f[u][1] = head[u]==-1?0:INF;for(int e = head[u]; e!=-1; e = E[e].next) {int v = E[e].v;int w = E[e].w;   dfs(v, tot+w);   if(check(tot+w+f[v][1])) {f[u][0] = max(f[u][0], w+f[v][1]);}   if(check(tot+w+f[v][0])) {f[u][1] = min(f[u][1], w+f[v][0]);}}}   // 讀入加速// http://www.bianceng.cninline int nextInt() {char c = getchar();while (!isdigit(c)) c = getchar();int x = 0;while (isdigit(c)) {x = x*10+c-'0';c = getchar();}return x;}   int main(){   while (~scanf("%d%d%d", &n, &l, &r)) {   initAdj();for (int i = 0; i < n - 1; ++i) {int u, v, w;u = nextInt();v = nextInt();w = nextInt();addEdge(u,v,w);}   dfs(0, 0);   if (!check(f[0][0])) {puts("Oh, my god!");} else {printf("%d\n", f[0][0]);}}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.