UVa 11183 Teen Girl Squad 朱劉算法求固定根最小樹形圖

題目鏈接:UVa 11183


分析:使用朱劉算法求固定根最小樹形圖


代碼如下:

// uva 11183
#include <cstdio>
#include <cstring>

const int N = 1111;
const int M = 44444;
const int inf = 0x7fffffff;
int pre[N], ID[N], vis[N], In[N], tot;

struct Edge
{
    int u, v, cost;
} E[M];

void addedge(int a, int b, int c) { E[tot].u = a, E[tot].v = b, E[tot++].cost = c; }
// void addedge(int a, int b, int c) { E[tot++] = {a, b, c}; } // 需要支持c++11或gnu++11

int Directed_MST(int root, int NV, int NE)
{
    int ret = 0;
    while(true) {
        // 1.找最小入邊
        for(int i = 0; i < NV; i++) In[i] = inf;
        for(int i = 0; i < NE; i++) {
            int u = E[i].u;
            int v = E[i].v;
            if(E[i].cost < In[v] && u != v) {
                pre[v] = u;
                In[v] = E[i].cost;
            }
        }
        for(int i = 0; i < NV; i++) {
            if(i == root) continue;
            if(In[i] == inf) return -1; // 除了跟以外有點沒有入邊,則根無法到達它
        }
        // 2.找環
        int cntnode = 0;
        memset(ID, -1, sizeof(ID));
        memset(vis, -1, sizeof(vis));
        In[root] = 0;
        for(int i = 0; i < NV; i++) { // 標記每個環
            ret += In[i];
            int v = i;
            while(vis[v] != i && ID[v] == -1 && v != root) {
                vis[v] = i;
                v = pre[v];
            }
            if(v != root && ID[v] == -1) {
                for(int u = pre[v] ; u != v ; u = pre[u]) {
                    ID[u] = cntnode;
                }
                ID[v] = cntnode++;
            }
        }
        if(cntnode == 0) break; // 無環
        for(int i = 0; i < NV; i++) {
            if(ID[i] == -1) ID[i] = cntnode++;
        }
        // 3.縮點,重新標記
        for(int i = 0; i < NE; i++) {
            int v = E[i].v;
            E[i].u = ID[E[i].u];
            E[i].v = ID[E[i].v];
            if(E[i].u != E[i].v) {
                E[i].cost -= In[v];
            }
        }
        NV = cntnode;
        root = ID[root];
	}
	return ret;
}

int main()
{
    // freopen("in", "r", stdin);
    int a, b, c, n, m;
    int t, k = 1;
    scanf("%d", &t);
    while(t--) {
        tot = 0;
        scanf("%d%d", &n, &m);
        for(int i = 0; i < m; i++) {
            scanf("%d%d%d", &a, &b, &c);
            addedge(a, b, c);
        }
        int as = Directed_MST(0, n, m);
        if(~as) printf("Case #%d: %d\n", k++, as);
        else printf("Case #%d: Possums!\n", k++);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章