1. 程式人生 > >luogu P2016 戰略遊戲

luogu P2016 戰略遊戲

嘟嘟嘟

 

樹形dp水題啦。

剛開始以為和[SDOI2006]保安站崗這道題一樣,然後交上去WA了。

仔細想想還是有區別的,一個是能看到相鄰點,一個是能看到相鄰邊。對於第一個,可以(u, v)兩個點都不放,然而對於這道題就不行了。

不過dp方程更簡單:dp[u][0/1]表示u這個點不放/放士兵的最優答案。那麼:

不放:則u的所有兒子必須放,才能覆蓋所有相鄰的邊:dp[u][0] = Σdp[v][1]

放:則u的兒子可放可不放:dp[u][1] = Σmin{dp[v][0], dp[v][1]} + 1

完啦

 1 #include<cstdio>
 2
#include<iostream> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 #include<cstdlib> 7 #include<cctype> 8 #include<vector> 9 #include<stack> 10 #include<queue> 11 using namespace std; 12 #define enter puts("") 13 #define space putchar(' ') 14
#define Mem(a, x) memset(a, x, sizeof(a)) 15 #define rg register 16 typedef long long ll; 17 typedef double db; 18 const int INF = 0x3f3f3f3f; 19 const db eps = 1e-8; 20 const int maxn = 1505; 21 inline ll read() 22 { 23 ll ans = 0; 24 char ch = getchar(), last = ' '; 25 while(!isdigit(ch)) {last = ch; ch = getchar();}
26 while(isdigit(ch)) {ans = (ans << 1) + (ans << 3) + ch - '0'; ch = getchar();} 27 if(last == '-') ans = -ans; 28 return ans; 29 } 30 inline void write(ll x) 31 { 32 if(x < 0) x = -x, putchar('-'); 33 if(x >= 10) write(x / 10); 34 putchar(x % 10 + '0'); 35 } 36 37 int n; 38 39 struct Edge 40 { 41 int nxt, to; 42 }e[maxn << 1]; 43 int head[maxn], ecnt = -1; 44 void addEdge(int x, int y) 45 { 46 e[++ecnt] = (Edge){head[x], y}; 47 head[x] = ecnt; 48 } 49 50 ll dp[maxn][2]; 51 void dfs(int now, int f) 52 { 53 dp[now][1] = 1; 54 for(int i = head[now], v; i != -1; i = e[i].nxt) 55 { 56 v = e[i].to; 57 if(v == f) continue; 58 dfs(v, now); 59 dp[now][0] += dp[v][1]; 60 dp[now][1] += min(dp[v][0], dp[v][1]); 61 } 62 } 63 64 int main() 65 { 66 Mem(head, -1); 67 n = read(); 68 for(int i = 1; i <= n; ++i) 69 { 70 int x = read(), k = read(); x++; 71 for(int j = 1; j <= k; ++j) 72 { 73 int y = read(); y++; 74 addEdge(x, y); addEdge(y, x); 75 } 76 } 77 dfs(1, 0); 78 write(min(dp[1][0], dp[1][1])), enter; 79 return 0; 80 }
View Code