[Codeforces 893F. Subtree Minimum Query]线段树合并

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ACMore_Xiong/article/details/78659862

[Codeforces 893F. Subtree Minimum Query]线段树合并

分类:Data Structure SegMent Tree Merge

1. 题目链接

[Codeforces 893F. Subtree Minimum Query]

2. 题意描述

一个n个节点的有根树,每个节点有一个边权ai,每条边的边长为1。然后是m个询问。对于第i次询问,求在点xi为根节点的子树中且到点xi距离小于等于ki的点权最小值。询问要求强制在线。
数据范围:1n105,1m106,1ai109

3. 解题思路

qwb说这是线段树合并的经典套路题。
我第一次写线段树合并。合并的地方写残了。无限RE...

思路就是对每个节点建一个线段树,这个线段树维护了该节点为根节点的子树的最小点权。自底向上,将子节点的线段树合并到父节点上去。太精妙了。

4. 实现代码

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double lb;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ull, ull> puu;
typedef pair<lb, lb> pbb;
typedef vector<int> vi;

const int inf = 0x3f3f3f3f;
const ll infl = 0x3f3f3f3f3f3f3f3fLL;
template<typename T> inline void umax(T &a, T b) { a = max(a, b); }
template<typename T> inline void umin(T &a, T b) { a = min(a, b); }
template<typename T> inline T randIntv(const T& a, const T& b) { return (T)rand() % (b - a + 1) + a; }
void debug() { cout << endl; }
template<typename T, typename ...R> void debug (T f, R ...r) { cout << "[" << f << "]"; debug (r...); }

const int MAXN = 100005;
int n, m, r;
ll a[MAXN];
struct Edge {
    int v, next;
} edge[MAXN << 1];
int head[MAXN], etot, dep[MAXN], null;
void ini(int n) {
    etot = 0;
    for (int i = 0; i <= n; ++i) head[i] = -1;
}
void ins(int u, int v) {
    edge[etot] = Edge{v, head[u]};
    head[u] = etot ++;
}
#define lch     nd[rt].ch[0]
#define rch     nd[rt].ch[1]
struct TNode {
    ll val;
    int ch[2];
    void ini() { ch[0] = ch[1] = 0; val = infl; }
} nd[MAXN * 50];
int root[MAXN], rsz;

void pushUp(int rt) {
    nd[rt].val = min(nd[lch].val, nd[rch].val);
}

void update(int p, ll v, int l, int r, int& rt) {
    nd[rt = ++ rsz].ini();
    if (l == r) {
        nd[rt].val = v;
        return;
    }
    int md = (l + r) >> 1;
    if (p <= md) update(p, v, l, md, lch);
    else update(p, v, md + 1, r, rch);
    pushUp(rt);
}

int merge(int u, int v) {
    if (!v) return u;
    if (!u) return v;
    int ret = ++ rsz; nd[ret].ini();
    nd[ret].ch[0] = merge(nd[u].ch[0], nd[v].ch[0]);
    nd[ret].ch[1] = merge(nd[u].ch[1], nd[v].ch[1]);
    nd[ret].val = min(nd[u].val, nd[v].val);
    return ret;
}

void dfs(int u, int fa, int d) {
    dep[u] = d;
    update(dep[u], a[u], 1, n, root[u]);
    for (int i = head[u]; ~i; i = edge[i].next) {
        int v = edge[i].v;
        if (v == fa) continue;
        dfs(v, u, d + 1);
        root[u] = merge(root[u], root[v]);
    }
}

ll query(int L, int R, int l, int r, int rt) {
    if (L <= l && r <= R) return nd[rt].val;
    int md = (l + r) >> 1; ll ret = infl;
    if (L <= md) umin(ret, query(L, R, l, md, nd[rt].ch[0]));
    if (R > md) umin(ret, query(L, R, md + 1, r, nd[rt].ch[1]));
    return ret;
}

int main() {
#ifdef ___LOCAL_WONZY___
    freopen("input.txt", "r", stdin);
#endif // ___LOCAL_WONZY___
    int u, v, p, q, x, k;
    ll last = 0;
    scanf("%d %d", &n, &r);
    for (int i = 1; i <= n; ++i) scanf("%lld", &a[i]);
    ini(n);
    for (int i = 2; i <= n; ++i) {
        scanf("%d %d", &u, &v);
        ins(u, v), ins(v, u);;
    }
    rsz = 0;
    nd[null = 0].ini();
    dfs(r, r, 1);
    scanf("%d", &m);
    for (int i = 1; i <= m; ++i) {
        scanf("%d %d", &p, &q);
        x = (p + last) % n + 1, k = (q + last) % n;
        last = query(dep[x], dep[x] + k, 1, n, root[x]);
        printf("%lld\n", last);
    }
#ifdef ___LOCAL_WONZY___
    cout << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC * 1000 << "ms." << endl;
#endif // ___LOCAL_WONZY___
    return 0;
}
展开阅读全文

fw: Total Subtree Cost

07-01

[b]Total Subtree Cost[/b] rnrnDuring the delivery of Solid Quality’s DBA Bootcamp, I go over query performance tuning and one of the items we discuss that is very useful when tuning queries is the TotalSubtreeCost value. To be fair, it is TotalSubtreeCost when dealing with the text-based execution plans, actual or estimated, but it has a different name when dealing with the graphical plans: Estimated Subtree Cost. It has a third name when dealing with XML showplans just to make everything even more confusing: StatementSubTreeCost.rnrnSo what is TotalSubtreeCost? TotalSubtreeCost is the cost of the query and the cost of each of the statements of the query. If you are interested in how the optimizer determines the cost of a query, you can find the formulas for both SQL Server 2000 and SQL Server 2005 in this nice white paper put out by Microsoft: Batch Compilation, Recompilation, and Plan Caching Issues in SQL Server 2005. While trying to figure out the cost of a query with the formula is interesting, I always tell my students that unless you live in your mother’s basement and have nothing better to do over the weekend, just take the cost of a query at its face value and know that the cost of the query can pretty much be compared across servers and executions of the query, there will be some differences but it will be close enough to know that a query with a cost of 500 is always going to be a more complex query than one with a cost of 10.rnrnSo what do I do with the cost of a query when I am tuning the query? First you have to realize that the value of TotalSubtreeCost is going to be cumulative from the first statement execute up to the last statement executed in the query. Then you have to realize that the showplan output that you are seeing is not in order of which statements execute first. Putting these two together, you must reorder the statements, find the TotalSubtreeCost of the first statement, subtract the value of the first statement from the value of the second statement that executes in order to find what the cost of the second statement is – remember the value is cumulative from the first statement to the last so the value shown for each individual statements are the values for all the statements that have previously execute plus the cost for that individual statement.rnrnConfused? Don’t worry, I am writing this and I get confused. It is not easy to figure out the cost of an individual statement using TotalSubtreeCost, what you can do is take the overall value for this column from the top of the execution plan and compare it to different executions of the query after you have done some work on it. As the value for TotalSubtreeCost goes down, you are making the query less expensive to execute. Usually the less expensive the query is, the better optimized it is – I said usually, not always.rnrnAnother thing you can do is to look for large leaps in the value of this column between two different statements. An example would be statement 4 executes first with a cost of .0078 and statement 3 executes next but the TotalSubtreeCost value now reads 100.0078. This can give you a clue that statement 3 had an individual cost of 100 and may be a good candidate for optimization. Whether you can actually do anything to statement 3 is a different story.rnrnGiven that the higher cost queries are usually more complex and often more work to optimize them, how can you use this to your advantage? One of the things I am toying with is searching through the query DMVs and pulling out a list of queries with the highest execution cost. I can then take these queries and return a list of queries with the most reads, most writes, most recompiles, highest CPU usage, and most duration. Using the TotalSubtreeCost value as a filter will help me eliminate queries that are under 100 in value, a good starting point for most environments as a query with a cost of 100 or more seems to be the queries that will get the attention of the DBA or developer as not performing at an optimal level. You will still need to worry about the queries that are under a cost of 100 if those queries are executed hundreds or thousands of times a second. Another listing of queries you constantly need to have on hand are queries grouped by number of executions per second. This allows you to work on a query even if it only takes 3 seconds to complete but runs hundreds of times a seconds which makes it one of your highest resource consumers.rnrnSo how do I find the queries with high TotalSubtreeCost values? First you will need to create a nice little function that Stuart Ozer from Microsoft supplied in this nice little Microsoft Customer Advisory Team blog posting: Obtaining Statement-Level Query Plans. This function will take the XML formatting of the showplans as they exist in the DMVs and parse it out into something useful. After creating this function in your database, you simply utilize the function with the a few other DMVs in a statement like this:rnrn[code=SQL] rnrnselect rnrnq.dbidrnrn,q.objectidrnrn,pln.statement_textrnrn,pln.statement_planrnrn,pln.statement_typernrn,pln.statement_subtree_costrnrn,pln.statement_estimated_rowsrnrn,pln.statement_optimization_levelrnrnFROM sys.dm_exec_cached_plans qsrnrnCROSS APPLY statement_level_query_plan(plan_handle) pln rnrnCROSS APPLY sys.dm_exec_sql_text(plan_handle) qrnrnWHERE pln.statement_subtree_cost > 100rnrnORDER BY pln.statement_subtree_cost DESC[/code]rnrnrnAfter executing this simple query, you should get back a listing of all queries with a cost of greater than 100. You can then do some more work and use this listing of queries to filter out lower cost queries when creating listings of potential queries that you need to optimize. rnrnHint: Research sys.dm_exec_query_stats to find out how you can pull execution out of the procedure cache and group them by reads, writes, CPU usage, recompiles, and duration.rnrn I know this blog posting was not very detailed and probably left you with more questions than answers, but that is what it was designed to do. The more work you have to do to answer those questions, the more you will actually remember the information in this blog the next time you need it.rnrnUntil next time, have a great day and remember me for your SQL Server training needs. rnrn[align=right]Randy Dyess[/align]rn 论坛

unexpected end of subtree 原因是什么

09-09

2011-09-09 10:36:29,052 FATAL [com.intple] ("http-nio-8080"-exec-10:) Internal error: unexpected end of subtree [select distinct p.id, (select coalesce(case when i3.id.languageId = 2 then i3.content else null end)) as categoryName from com.intple.billing.server.product.db.ProductDTO p left join p.productCategoryDtoSet c2, com.intple.billing.server.util.db.InternationalDescriptionDTO i3 where 1=1 and p.parent is null and p.deleted=:deleted and p.entity.id=:entityid and i3.id.tableId=(select id from com.intple.billing.server.util.db.BillingTable where name='product_category') and i3.id.psudoColumn='description' and i3.id.foreignId=c2.id order by convert_gbk(categoryName) asc]rnorg.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree [select distinct p.id, (select coalesce(case when i3.id.languageId = 2 then i3.content else null end)) as categoryName from com.intple.billing.server.product.db.ProductDTO p left join p.productCategoryDtoSet c2, com.intple.billing.server.util.db.InternationalDescriptionDTO i3 where 1=1 and p.parent is null and p.deleted=:deleted and p.entity.id=:entityid and i3.id.tableId=(select id from com.intple.billing.server.util.db.BillingTable where name='product_category') and i3.id.psudoColumn='description' and i3.id.foreignId=c2.id order by convert_gbk(categoryName) asc]rn at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)rn at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)rn at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)rn at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:261)rn at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)rn at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)rn at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:101)rn at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:80)rn at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:94)rn at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)rn at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)rn at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1651) 论坛

没有更多推荐了,返回首页