標籤:
clj在某場hihoCoder比賽中的一道題,表示clj的數學題實在6,這道圖論貌似還算可以。。。
題目連結:http://hihocoder.com/problemset/problem/1167
由於是中文題目,題意不再贅述。
對於任意兩條小精靈的活動路徑a和b,二者相交的判斷條件為b的兩個端點的LCA在a的路徑上;那麼我們可以首先將每個活動路徑端點的LCA離線預先處理出來,對每個節點LCA值+1。
然後以某個節點(我選擇的是節點1)為根進行深搜,算出一條從節點1到節點x的LCA值和,那麼任意路徑a(假設其兩端點分別是A和B)上的節點個數就是sum[A] + sum[B] - 2 * sum[LCA(A,B)]。
最後,對於某些點,如果它是不止一條路徑的LCA,那麼我們只需要對最終答案乘以C(LCAnum, 2)的組合數就好。
【PS:clj給出的題解中,採用了點分治+LCA的方式,雖然看懂了題意,但是表示對遞迴分治之後的路徑,如何求出其上的LCAnum,並沒有多好的想法,還望巨巨能指點一下,Thx~】
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5 typedef long long LL; 6 #define MAXN 100010 7 struct Edge { 8 int to, next; 9 } edge[MAXN << 1];10 struct Node {11 int to, next, num;12 } Query[MAXN << 1];13 struct node {14 int u, v, lca;15 } input[MAXN];16 int totEdge, totQuery, n, m;17 int headEdge[MAXN], headQuery[MAXN];18 int ancestor[MAXN], father[MAXN], LCAnum[MAXN], sum[MAXN];19 bool vis[MAXN];20 void addEdge(int from, int to) {21 edge[totEdge].to = to;22 edge[totEdge].next = headEdge[from];23 headEdge[from] = totEdge++;24 }25 void addQuery(int from, int to, int x) {26 Query[totQuery].to = to;27 Query[totQuery].num = x;28 Query[totQuery].next = headQuery[from];29 headQuery[from] = totQuery++;30 }31 void init() {32 memset(headEdge, -1, sizeof(headEdge));33 memset(headQuery, -1, sizeof(headQuery));34 memset(father, -1, sizeof(father));35 memset(vis, false, sizeof(vis));36 memset(sum, 0, sizeof(sum));37 memset(LCAnum, 0, sizeof(LCAnum));38 totEdge = totQuery = 0;39 }40 int find_set(int x) {41 if(x == father[x]) return x;42 else return father[x] = find_set(father[x]);43 }44 void union_set(int x, int y) {45 x = find_set(x); y = find_set(y);46 if(x != y) father[y] = x;47 }48 void Tarjan(int u) {49 father[u] = u;50 for(int i = headEdge[u]; i != -1; i = edge[i].next) {51 int v = edge[i].to;52 if(father[v] != -1) continue;53 Tarjan(v);54 union_set(u, v);55 }56 for(int i = headQuery[u]; i != -1; i = Query[i].next) {57 int v = Query[i].to;58 if(father[v] == -1) continue;59 input[Query[i].num].lca = find_set(v);60 }61 }62 void DFS(int u, int pre) {63 vis[u] = 1;64 sum[u] = sum[pre] + LCAnum[u];65 for(int i = headEdge[u]; i != -1; i = edge[i].next) {66 int v = edge[i].to;67 if(vis[v]) continue;68 DFS(v, u);69 }70 }71 int main() {72 init();73 scanf("%d%d", &n, &m);74 for(int i = 0; i < n - 1; i++) {75 int a, b;76 scanf("%d%d", &a, &b);77 addEdge(a, b); addEdge(b, a);78 }79 for(int i = 0; i < m; i++) {80 int a, b;81 scanf("%d%d", &a, &b);82 input[i].u = a, input[i].v = b;83 addQuery(a, b, i); addQuery(b, a, i);84 }85 Tarjan(1);86 for(int i = 0; i < m; i++)87 LCAnum[input[i].lca]++;88 DFS(1, 0);89 LL ans = 0;90 for(int i = 0; i < m; i++) {91 ans += (sum[input[i].u] + sum[input[i].v] - 2 * sum[input[i].lca]);92 }93 for(int i = 1; i <= n; i++) {94 ans += (LL)LCAnum[i] * (LCAnum[i] - 1) / 2;95 }96 printf("%lld\n", ans);97 return 0;98 }
View Code
轉載:)
hihoCoder挑戰賽11.題目4 : 高等理論電腦科學(LCA)