HDU 4677 query on Graph

Source: Internet
Author: User

Interval division.

This course has learned many new things & new ideas on this topic. The following describes the process of thinking in detail.

Question: Give a graph, each vertex has (1 ~ N), there are NQ queries, and the question range is L ~ R vertex set ~ After deleting all vertices and edges except R, there are several connected blocks.

Solution: Take x steps ~

1. interval Division: For L ~ The most violent method for queries in each interval of R is to calculate from L to r one by one. The complexity is O (Q * n). For queries, q = 3 W, if the question with the interval length n = 3 W must time out, consider optimization.

For each query, we consider the overlapping parts of their LR ranges (if they do not overlap, it would be too many (n) seconds). Can the time of overlapping parts be optimized.

For the left endpoint L with the same range, we can sort them by the right endpoint from small to large, so for a query, it only has a part of the range on the right than the previous query, then, you can use the result of the previous query range to calculate the answer to the next interval. Here, you can save the repeated calculation of the overlapping intervals.

However, we know that the question will not honestly ask you about the left-side aligned range, so we will cut them neatly. For example, the right part of the split line can be optimized through step-by-step calculation. The left part can be obtained by brute force, and then the Left and Right sections can be merged.

We also know the fact that some intervals do not overlap, so their results will not affect each other, so we have to separate them. We will set the entire range 1 ~ N is divided into X segments. If the left endpoint is placed together with the line segments of the same segment, it takes O (n) time to process the right segment, in the worst case, the length of the block must be multiplied by the number of queries in the block. The total complexity is O (x * n + Q * n/X ).

Then, the selection of X will minimize the time complexity of this polynomial. In the same scale of N and Q, it is obvious that when x = SQRT (n), the time complexity is O (n * SQRT (n) + Q * SQRT (n )). (PS: If you have any questions about x = SQRT (N), list the equations and obtain a derivative ).

To sum up the interval Division: first, offline ~ Divide the N range into SQRT (n) segments, sort the queries of the Left endpoint in each segment by the right endpoint from small to large, and then obtain the brute force query of the left part, the right part is obtained using the result of the previous query, and the left and right intervals are the answers to the current query.

2. Maintain the number of connected blocks:

Use and query sets to count the number of connected blocks. For this question, we chose to use the interval division method to split the inquiry into the left and right sections. The question is how to merge them. First, the left and right parts are maintained by the query set. We need to keep the right part of the query set independent of the left part, so that it can be passed to the next query. Therefore, the question is how to obtain the results of merging two sets without modifying the right part and querying the set.

The simple idea is to copy the FA array of the right part and check the set, and then merge and solve the problem. However, the copy cost is O (n * q), which is not feasible. Now let's take a look at how many merge operations are required for the merge of the left and right sides: the left part has a maximum of SQRT (n) points, and a total of m edges. Due to random data, the edge is evenly distributed. The vertices in the left part have a total of M/SQRT (n) edges, that is, the right part has a maximum of M/SQRT (N) vertices and left vertices have edges. If you can copy only the M/SQRT (n) vertices, the merging can be completed, and the time complexity is also small, is it tempting.

Consider setting a vis array: When the left and right sides are merged, we will ask whether the current endpoint has been copied to a temporary and queried set for the two endpoints of an edge. If not, copy its information from the original dataset. Well, now the point is: if the VIS array is used to mark whether to copy, it will take O (n) Time to re-assign 0 to each query? This is obviously unnecessary, because each query has a unique ID, which is used to mark the VIS array. the ID of the new query must not be equal to any value in the VIS array, of course, you don't need to clear 0 every time.

Provide your Ms code .. The first time I wrote the interval division, I read the sample code and happily handed it over directly. As a result, I opened a small RE and orz in the adjacent table.

The original offline processing interval inquiry method, in addition to the line segment tree and tree array, has such a magical thing, again orz.

#include <stdio.h>#include <string.h>#include <algorithm>#include <math.h>using namespace std;#define REP(i,a,b) for(int i=(a); i<(b); i++)#define clr(a,b) memset(a,b,sizeof(a))typedef long long lld;const int INF = ~0u>>1;const int MAXN = 30010;struct Edge {    int v, next;}g[MAXN*10];int head[MAXN], tot;int n,m,nq;struct Q {    int l, r, id;    int b;    bool operator < (const Q &tt) const {        if(b == tt.b) return r < tt.r;        return b < tt.b;    }}q[MAXN];int ans[MAXN];int fa[MAXN];int L,R;int vis[MAXN];int tfa[MAXN];int block_size;int rcnt;int now;int Find(int x) {    return fa[x] = (fa[x] == x) ? x : Find(fa[x]);}int merge(int a, int b) {    a = Find(a);    b = Find(b);    if(a == b) return 0;    fa[a] = b;    return 1;}int Tfind(int x) {    if(vis[x] != now) {        tfa[x] = fa[x];        vis[x] = now;    }    return tfa[x] = (tfa[x] == x) ? x : Tfind(tfa[x]);}int Tmerge(int a, int b) {    a = Tfind(a);   b = Tfind(b);    if(a == b) return 0;    tfa[a] = b;    return 1;}int work(int l, int r, int ss) {    if(ss != L/block_size - 1) {        L = (ss+1) * block_size;        rcnt = 0;        R = L+1;        for(int i=L-block_size+1; i<=L; i++) fa[i] = i;    }    for(; R<=r; R++) {        fa[R] = R;        rcnt ++;        for(int p=head[R]; ~p; p=g[p].next) {            int v = g[p].v;            if(v >= R || v <= L) continue;            if(merge(R,v)) rcnt --;        }    }    int tr = min(r,L);    int ret = 0;    if(r>L) ret += rcnt;    for(int i=l; i<=tr; i++) {        ret ++;        for(int p=head[i]; ~p; p=g[p].next) {            int v = g[p].v;            if(v<=i || v>r) continue;            if(Tmerge(i,v)) ret --;        }    }    return ret;}void add_edge(int a, int b) {    g[tot].v = b;    g[tot].next = head[a];    head[a] = tot ++;}int main() {    int cas, ca = 0;    scanf("%d", &cas);    while(cas--) {        clr(head, -1);        tot = 0;        scanf("%d%d", &n, &m);        int a,b;        REP(i,0,m) {            scanf("%d%d", &a, &b);            add_edge(a,b);            add_edge(b,a);        }        scanf("%d", &nq);        block_size = (int)sqrt(n*1.0);        REP(i,0,nq) {            scanf("%d%d", &q[i].l, &q[i].r);            q[i].b = q[i].l/block_size;            q[i].id = i;        }        sort(q,q+nq);        L = R = -1;        clr(vis,-1);        REP(i,0,nq) {            now = i;            ans[q[i].id] = work(q[i].l,q[i].r,q[i].b);        }        printf("Case #%d:\n", ++ca);        REP(i,0,nq) printf("%d\n", ans[i]);    }    return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.