UVaLive 10859 Placing Lampposts (树形DP)

题意:给定一个无向无环图,要在一些顶点上放灯使得每条边都能被照亮,问灯的最少数,并且被两盏灯照亮边数尽量多。

析:其实就是一个森林,由于是独立的,所以我们可以单独来看每棵树,dp[i][0] 表示不在 i 点放灯,dp[i][1] 表示在 i 点放灯,很简单的一个DP

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#define debug() puts("++++");
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1000 + 5;
const int mod = 2000;
const int dr[] = {-1, 1, 0, 0};
const int dc[] = {0, 0, 1, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
    return r >= 0 && r < n && c >= 0 && c < m;
}
bool vis[maxn];
int dp[maxn][2];
vector<int> G[maxn];

void dfs(int u){
    vis[u] = true;
    dp[u][0] = 0;
    dp[u][1] = mod;
    for(int i = 0; i < G[u].size(); ++i){
        int v = G[u][i];
        if(vis[v])  continue;
        dfs(v);
        dp[u][0] += dp[v][1] + 1;
        dp[u][1] += dp[v][0] < dp[v][1] ? dp[v][0] + 1 : dp[v][1];
    }
}

int main(){
    int T;  cin >> T;
    while(T--){
        scanf("%d %d", &n, &m);
        for(int i = 0; i < n; ++i)  G[i].clear();
        for(int i = 0; i < m; ++i){
            int u, v;
            scanf("%d %d", &u, &v);
            G[u].push_back(v);
            G[v].push_back(u);
        }

        memset(vis, false, sizeof vis);
        int ans1 = 0, ans2 = 0;
        for(int i = 0; i < n; ++i)  if(!vis[i]){
            dfs(i);
            ans1 += min(dp[i][0], dp[i][1]) / mod;
            ans2 += min(dp[i][1], dp[i][0]) % mod;
        }
        int ans3 = m - ans2;
        printf("%d %d %d
", ans1, ans3, ans2);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/dwtfukgv/p/6530590.html