1. 程式人生 > >Codeforces 911F 貪心

Codeforces 911F 貪心


分析:先求出樹的直徑,以這個直徑上的節點作為主幹。

假設兩個端點分別為x,y,求其他任意葉子節點z到另一個葉子節點的最長距離即為max{ d(x,z), d(y,z) }

該解法的正確性我無法給出證明,但畫圖看看應該就不難理解的。

程式碼如下:

#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;

typedef long long LL;
const int maxn = 2e5+10;
struct answer{
   int u,v;
}a[maxn];
vector<int> G[maxn];
bool v[maxn];
int d[maxn],pre[maxn];
int n,tot;
int root,leaf;
LL ans;

void init(){
   for (int i=1; i<=n; i++) G[i].clear();
   tot = 0;
   int u,v;
   for (int i=1; i<n; i++) {
      scanf("%d %d",&u,&v);
      G[u].push_back(v);
      G[v].push_back(u);
   }
   ans = 0;
}

void dfs(int u, int fa){
    d[u] = d[fa]+1;
    pre[u] = fa;
    for (int i=0; i<G[u].size(); i++) if (G[u][i]!=fa) dfs(G[u][i],u);
}

void Find(int x, int df, int dr, bool flag = 1){
    for (int i=0; i<G[x].size(); i++) {
        if (G[x][i] == pre[x] || v[G[x][i]]) continue;
        Find(G[x][i],df+1,dr+1);
    }
    if (flag) {
        if (df>dr) {
            a[tot].u = leaf;
            a[tot].v = x;
            ans += df;
        }
        else {
            a[tot].u = root;
            a[tot].v = x;
            ans += dr;
        }
        tot++;
    }
}

int main(){
    while (scanf("%d",&n)==1){
        init();

        d[0] = 0;
        root = 1;
        dfs(root,0);
        for (int i=1; i<=n; i++) if (d[root]<d[i]) root = i;
        leaf = 1;
        dfs(root,0);
        for (int i=1; i<=n; i++) if (d[leaf]<d[i]) leaf = i;
        memset(v,0,sizeof(v));
        int x = leaf;
        while (1){
            v[x] = 1;
            Find(x,d[leaf]-d[x],d[x]-1,0);
            if (x == root) break;
            x = pre[x];
        }

        x = leaf;
        while (x!=root) {
            a[tot].u = root; a[tot].v = x; tot++;
            ans += d[x]-1;
            x = pre[x];
        }

        printf("%I64d\n",ans);
        for (int i=0; i<tot; i++) printf("%d %d %d\n",a[i].u,a[i].v,a[i].v);
    }
    return 0;
}