題意:給一棵無向圖構成的樹,要求刪除一些邊,再添加一些邊。使得圖中每個點直接和其它兩個點相連並且保證所有點是連通的。求至少要經過幾次操作才能滿足題意,每次操作爲刪除一條邊或者增加一條邊。
解法:分析可得,要滿足題意,那麼最後生成的圖肯定是所有點連成一個環。並且原圖中保留的邊越多,那麼添加的邊就越少。假設原圖有N個點,保留了X條邊,那麼最終的結果就是 (N-X)*2-1,所以求出最大的X就求出了結果。
定狀態:dp[x][0]爲根節點爲x的子樹,其中x不和其父節點相連,能保留的邊的最大數量;
dp[x][1]爲根節點爲x的子樹,其中x和其父節點相連,能保留的邊的最大數量。
在原樹中DP即可求得最大的X。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <memory.h>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <iostream>
#define ll long long
using namespace std;
const int N = 50;
vector<int> G[N];
int n, dp[N][N];
class RoadsReorganization {
public:
int MaxKeep(int x, bool c, int f) {
int &res = dp[x][c];
if (res != -1) return res;
int sum = 0;
for (int i = 0; i < G[x].size(); i++) {
int y = G[x][i];
if (y != f)
sum += MaxKeep(y, 0, x);
}
res = sum;
for (int i = 0; i < G[x].size(); i++) {
int y = G[x][i];
if (y == f) continue;
res = max(res, sum - MaxKeep(y, 0, x) + MaxKeep(y, 1, x) + 1);
}
if (c) return res;
for (int i = 0; i < G[x].size(); i++) {
int y = G[x][i];
if (y == f) continue;
for (int j = i + 1; j < G[x].size(); j++) {
int z = G[x][j];
if (z == f) continue;
res = max(res, sum - MaxKeep(y, 0, x) - MaxKeep(z, 0, x) +
MaxKeep(y, 1, x) + MaxKeep(z, 1, x) + 2);
}
}
return res;
}
int minDaysCount(vector<string> kingdom) {
n = kingdom.size();
for (int i = 0; i < n; i++) G[i].clear();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (kingdom[i][j] == '1')
G[i].push_back(j);
}
}
memset(dp, -1, sizeof(dp));
return (n - MaxKeep(0, 0, -1)) * 2 - 1;
}
};