南昌邀请赛 Distance on the tree(树链剖分)(邻接表建立模板)

142 篇文章 3 订阅

DSM(Data Structure Master) once learned about tree when he was preparing for NOIP(National Olympiad in Informatics in Provinces) in Senior High School. So when in Data Structure Class in College, he is always absent-minded about what the teacher says.

The experienced and knowledgeable teacher had known about him even before the first class. However, she didn't wish an informatics genius would destroy himself with idleness. After she knew that he was so interested in ACM(ACM International Collegiate Programming Contest), she finally made a plan to teach him to work hard in class, for knowledge is infinite.

This day, the teacher teaches about trees." A tree with nn nodes, can be defined as a graph with only one connected component and no cycle. So it has exactly n-1n−1 edges..." DSM is nearly asleep until he is questioned by teacher. " I have known you are called Data Structure Master in Graph Theory, so here is a problem. "" A tree with nn nodes, which is numbered from 11 to nn. Edge between each two adjacent vertexes uu and vv has a value w, you're asked to answer the number of edge whose value is no more than kk during the path between uu and vv."" If you can't solve the problem during the break, we will call you DaShaMao(Foolish Idiot) later on."

The problem seems quite easy for DSM. However, it can hardly be solved in a break. It's such a disgrace if DSM can't solve the problem. So during the break, he telephones you just for help. Can you save him for his dignity?

Input

In the first line there are two integers n,mn,m, represent the number of vertexes on the tree and queries(2 \le n \le 10^5,1 \le m \le 10^52≤n≤105,1≤m≤105)

The next n-1n−1 lines, each line contains three integers u,v,wu,v,w, indicates there is an undirected edge between nodes uu and vv with value ww. (1 \le u,v \le n,1 \le w \le 10^91≤u,v≤n,1≤w≤109)

The next mm lines, each line contains three integers u,v,ku,v,k , be consistent with the problem given by the teacher above. (1 \le u,v \le n,0 \le k \le 10^9)(1≤u,v≤n,0≤k≤109)

Output

For each query, just print a single line contains the number of edges which meet the condition.

样例输入1复制

3 3
1 3 2
2 3 7
1 3 0
1 2 4
1 2 7

样例输出1复制

0
1
2

样例输入2复制

5 2
1 2 1000000000
1 3 1000000000
2 4 1000000000
3 5 1000000000
2 3 1000000000
4 5 1000000000

样例输出2复制

2
4

 

题意:

n,m表示n个顶点m条询问然后是n-1行表示n-1条边和m条询问

每个询问包含u,v,k表示从u到v的路径上有多少条边的值不超过k

所构图是个树 没有环

 

解题思路:

超时了,留坑。。

 

我的想法有点简单,直接邻接表存图然后bfs,如果路径上有符合条件的边就step++

 

代码:

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

int n,m,st,en,k;
int head[100010],book[100010];
int cnt;

struct node
{
	int x,step;
};

struct e
{
	int u,v,w,next;
} edge[100010];


void add(int u,int v,int w)//向所要连接的表中加入边
{
    edge[cnt].u=u;
    edge[cnt].v=v;
    edge[cnt].w=w;
    edge[cnt].next=head[u];
    head[u]=cnt++;
}

node getnode(int x,int step)
{
	node q;
	q.x=x;
	q.step=step;
	return q;
}

int bfs(int st,int step)
{
	queue<node> q;
	node now;
	q.push(getnode(st,step));
	while(!q.empty())
	{
		now=q.front();
		q.pop();
		int tk=head[now.x];
		if(edge[tk].u==en) return now.step;
		while(book[edge[tk].v]==0&&tk!=-1)
		{
			book[edge[tk].v]=1;
			int tstep=now.step;
			if(edge[tk].w<=k)
			{
				tstep++;
			}
			q.push(getnode(edge[tk].v,tstep));
			
			tk=edge[tk].next;
		}
	}
	return -1;
}

int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		
		int u,v,w;
		memset(head,-1,sizeof(head));
		cnt=1;
		for(int i=1;i<=n-1;i++)
		{
			scanf("%d%d%d",&u,&v,&w);
			add(u,v,w);
			add(v,u,w);
		}
		
//		printf("****************\n");
//		for(int i=1;i<=n;i++)
//		{
//			int k=head[i];
//			while(k!=-1)
//			{
//				printf("%d %d %d\n",edge[k].u,edge[k].v,edge[k].w);
//				k=edge[k].next;
//			}
//		}
//		printf("****************\n");
		
		for(int i=1;i<=m;i++)
		{
			memset(book,0,sizeof(book));
			scanf("%d%d%d",&st,&en,&k);
			if(st==en)
			{
				printf("0\n");
				continue;
			}
			int sum=bfs(st,0);
			printf("%d\n",sum);
		}
	}
	return 0;
}

 

邻接表建立参考:

https://blog.csdn.net/haut_ykc/article/details/52177161

 


/*
*  构建邻接表模板
*
*/
#include<stdio.h>
#include<string.h>
int head[100100];//表头,head[i]代表起点是i的边的编号
int cnt;//代表边的编号
struct s
{
    int u;//记录边的起点
    int v;//记录边的终点
    int w;//记录边的权值
    int next;//指向上一条边的编号
}edge[100010];
void add(int u,int v,int w)//向所要连接的表中加入边
{
    edge[cnt].u=u;
    edge[cnt].v=v;
    edge[cnt].w=w;
    edge[cnt].next=head[u];
    head[u]=cnt++;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        int i;
        cnt=0;
        memset(head,-1,sizeof(head));//清空表头数组
        for(i=0;i<n;i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            add(u,v,w);
        }
        int u,v,w;
        scanf("%d",&u);
        for(i=head[u];i!=-1;i=edge[i].next)//输出所有与起点为u相连的边的终点和权值
        {
             v=edge[i].v;
             w=edge[i].w;
             printf("%d %d\n",v,w);
        }
    }
    return 0;
}

#include<stdio.h>  
#include<vector>  
using namespace std;  
  
#define SIZE 1000  
vector<vector<int> >adj(SIZE);  
int n,m;  
void init()  
{  
 scanf("%d%d",&n,&m);   
 int i,j;  
 int a,b;  
 for(i=1;i<=n;i++)  
 {  
  adj[i].clear(); //清除   
 }  
 for(i=1;i<=m;i++)  
 {  
  scanf("%d%d",&a,&b);  
  adj[a].push_back(b);  
  adj[b].push_back(a);   
 }  
}  
void print()  
{  
 int i;  
 int j;  
   
 for(i=1;i<=n;i++)  
 {  
    
  printf("dian %d:",i);  
  for(j=0;j<adj[i].size();j++)  
  {  
   printf("%d ",adj[i][j]);   
  }   
  printf("\n");  
 }  
}  
int main()  
{  
 int t;  
 scanf("%d",&t);  
 while(t--)  
 {  
    
  init();   
  print();  
 }  
   
 return 0;   
}  

 

 

补坑:

这道题看了题解需要用树链剖分来做,在学习树链剖分之前需要先学习线段树的相关知识。

树链剖分详解

代码(来自http://xzm2001.cn/archives/43/):

#include <iostream>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
#include <queue>
#include <stack>
#include <functional>
#include <map>
#include <set>
#include <bitset>
#include <ctime>
#include <complex>

#define INF 0x3f3f3f3f
#define memset0(x) memset(x, 0, sizeof(x))
#define memsetM1(x) memset(x, -1, sizeof(x))
#define memsetINF(x) memset(x, INF, sizeof(x))

using namespace std;

const int MAXN = 2e5 + 5;
int have[MAXN];
int wt[MAXN];
struct node
{
    node *l, *r;
    int v;
    node() : l(NULL), r(NULL), v(0){}
};
node nodes[MAXN * 3];
int tot;
node* newNode()
{
    nodes[tot] = node();
    return &nodes[tot++];
}
void pushUp(node* nd)
{
    if (nd->l)
    {
        nd->v = nd->l->v + nd->r->v;
    }
}
int n, q;
node* root;
void build(node* nd = root, int l = 1, int r = n)
{
    if (l != r)
    {
        int mid = (l + r) / 2;
        nd->l = newNode();
        nd->r = newNode();
        build(nd->l, l, mid);
        build(nd->r, mid + 1, r);
        pushUp(nd);
    }
    else
    {
        nd->v = 0;
    }
}
void init()
{
    tot = 0;
    root = newNode();
    build();
}

void modify(int l, int v, node* nd = root, int cl = 1, int cr = n)
{
    if (cl == cr)
    {
        nd->v = v;
        return;
    }
    int mid = (cl + cr) / 2;
    if (l <= mid)
    {
        modify(l, v, nd->l, cl, mid);
    }
    else if (l > mid)
    {
        modify(l, v, nd->r, mid + 1, cr);
    }
    pushUp(nd);
}
int query(int l, int r, node* nd = root, int cl = 1, int cr = n)
{
    if (l == cl && r == cr)
    {
        return nd->v;
    }
    int mid = (cl + cr) / 2;
    if (r <= mid)
    {
        return query(l, r, nd->l, cl, mid);
    }
    else if (l > mid)
    {
        return query(l, r, nd->r, mid + 1, cr);
    }
    else
    {
        return query(l, mid, nd->l, cl, mid) + query(mid + 1, r, nd->r, mid + 1, cr);
    }
}

vector<int> graph[MAXN];
int dfn = 1;
int edgeCnt;
int in[MAXN], out[MAXN], son[MAXN], sz[MAXN], fa[MAXN], top[MAXN], dep[MAXN];

void dfs1(int u = 1, int pre = -1)
{
    fa[u] = pre;
    sz[u] = 1;
    son[u] = 0;
    for (int i = 0; i < graph[u].size(); i++)
    {
        int v = graph[u][i];
        if (v == pre)
        {
            continue;
        }
        dep[v] = dep[u] + 1;
        dfs1(v, u);

        sz[u] += sz[v];
        if (son[u] == 0 || sz[v] > sz[son[u]])
        {
            son[u] = v;
        }
    }
}
void dfs2(int u = 1, int tp = 1)
{
    in[u] = dfn++;
    top[u] = tp;
    if (son[u])
    {
        dfs2(son[u], tp);
    }
    
    for (int i = 0; i < graph[u].size(); i++)
    {
        int v = graph[u][i];
        if (v != fa[u] && v != son[u])
        {
            dfs2(v, v);
        }
    }
    out[u] = dfn;
}

int queryV(int u, int v)
{
    int res = 0;
    while (top[u] != top[v])
    {
        if (dep[top[u]] < dep[top[v]])
        {
            swap(u, v);
        }
        // u
        res += query(in[top[u]], in[u]);
        u = fa[top[u]];
        if (u == -1)
        {
            break;
        }
    }
    if (u == -1)
    {
        while (top[v] != 1)
        {
            res += query(in[top[v]], in[v]);
            v = fa[top[v]];
        }
    }
    else
    {
        if (dep[u] < dep[v])
        {
            swap(u, v);
        }
        // u
        res += query(in[v], in[u]);
    }
    
    return res;
}

struct qry
{
    int u, v, w, ans, id;
    void input()
    {
        scanf("%d%d%d", &u, &v, &w);
    }
    bool operator<(const qry& b) const
    {
        return w < b.w;
    }
};
bool cmp(const qry& a, const qry& b)
{
    return a.id < b.id;
}
qry qs[MAXN];
pair<int, int> wts[MAXN];

int main()
{
#ifndef ONLINE_JUDGE
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
    int startTime = clock();
#endif

    scanf("%d%d", &n, &q);
    edgeCnt = n + 1;
    for (int i = 0; i < n - 1; i++)
    {
        int u, v, w;
        scanf("%d%d%d", &u, &v, &w);
        graph[u].push_back(edgeCnt);
        graph[v].push_back(edgeCnt);
        graph[edgeCnt].push_back(v);
        graph[edgeCnt].push_back(u);
        have[edgeCnt] = 1;
        wt[u] = wt[v] = INF;
        wt[edgeCnt] = w;
        edgeCnt++;
    }
    for (int i = 1; i < edgeCnt; i++)
    {
        wts[i] = { wt[i], i };
    }
    sort(wts + 1, wts + edgeCnt);
    n = 2 * n - 1;
    init();
    dfs1();
    dfs2();

    for (int i = 0; i < q; i++)
    {
        qs[i].input();
        qs[i].id = i;
    }
    sort(qs, qs + q);
    int cIndex = 1;
    for (int i = 0; i < q; i++)
    {
        if (i == 0 || qs[i].w != qs[i - 1].w)
        {
            for (; cIndex < edgeCnt; cIndex++)
            {
                if (wts[cIndex].first <= qs[i].w)
                {
                    modify(in[wts[cIndex].second], 1);
                }
                else
                {
                    break;
                }
            }
        }
        qs[i].ans =  queryV(qs[i].u, qs[i].v);
    }
    sort(qs, qs + q, cmp);
    for (int i = 0; i < q; i++)
    {
        printf("%d\n", qs[i].ans);
    }

#ifndef ONLINE_JUDGE
    printf("Time = %dms\n", clock() - startTime);
#endif
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值