HDU 2121 Ice_cream’s world II

妙啊!!
无定根的最小树形图,没想出来怎么做,看了题解后的第一感想就是,太妙了!!!

简单说一下无定根的最小树形图的基本思路。
首先建立一个虚根 r ,让虚根连向每一个实点,权值尽量大,一般选择实边边权和+1即可,以虚根建立最小树形图。
如果得到的答案大于等于两倍的 虚根到实点距离 , 那么就是不存在。因为最多只会存在一条。具体自己yy即可。

而我们需要找出的根节点,因为存在缩点,所以直接拿 虚根指向的结点是不行的。另一条有效且方便的方法就是在 虚根连实点的时候 一般人都会按顺序连,那么只要记录边的序号,然后 序号 – 点数即可。

题意:
无定根最小树形图裸题。

思路:
见上。

AC Code

#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>

#define each(i, n) for (int(i) = 0; (i) < (n); (i)++)
#define reach(i, n) for (int(i) = n - 1; (i) >= 0; (i)--)
#define range(i, st, en) for (int(i) = (st); (i) <= (en); (i)++)
#define rrange(i, st, en) for (int(i) = (en); (i) >= (st); (i)--)
#define fill(ary, num) memset((ary), (num), sizeof(ary))

using namespace std;
typedef long long ll;
typedef pair<int, int> pdd;
const int maxn = 1e3 + 5;
const int maxm = 1e4 + 5;
const int inf = 0x3f3f3f3f;

int in[maxn];
int pre[maxn], vis[maxn], id[maxn];

struct node {
    int u, v;
    ll cost;
} edges[maxm];

ll zhuliu(int root, int n, int m, int& key)
{
    ll res = 0;
    int u, v;
    while (true) {
        each(i, n + 1) in[i] = inf;
        each(i, m)
        {
            u = edges[i].u, v = edges[i].v;
            if (u != v && edges[i].cost < in[v]) {
                pre[v] = u;
                in[v] = edges[i].cost;
                if (u == root)
                    key = i;
            }
        }
        in[root] = 0;
        each(i, n) if (in[i] == inf) return -1;
        int scc = 0;
        fill(id, -1), fill(vis, -1);
        each(i, n)
        {
            res += in[i];
            v = i;
            while (vis[v] != i && id[v] == -1 && v != root) {
                vis[v] = i;
                v = pre[v];
            }
            if (v != root && id[v] == -1) {
                for (u = pre[v]; u != v; u = pre[u])
                    id[u] = scc;
                id[v] = scc++;
            }
        }
        if (scc == 0)
            break;
        each(i, n) if (id[i] == -1) id[i] = scc++;
        each(i, m)
        {
            v = edges[i].v;
            edges[i].u = id[edges[i].u];
            edges[i].v = id[edges[i].v];
            if (edges[i].u != edges[i].v)
                edges[i].cost -= in[v];
        }
        n = scc;
        root = id[root];
    }
    return res;
}

int main()
{
    int n, m, key;
    while (scanf("%d %d", &n, &m) != EOF) {
        ll sum = 0;
        each(i, m)
        {
            scanf("%d %d %lld", &edges[i].u, &edges[i].v, &edges[i].cost);
            sum += edges[i].cost;
        }
        sum++;
        each(i, n) edges[i + m] = (node){ n, i, sum };
        ll res = zhuliu(n, n + 1, m + n, key);
        if (res == -1 || res - sum >= sum)
            puts("impossible");
        else
            printf("%lld %d\n", res - sum, key - m);
        puts("");
    }
    return 0;
}