Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

不知道其他人说的不连通是什么意思。。

Posted by Ruby931031 at 2012-07-09 16:37:13 on Problem 1986
In Reply To:真不知道测试数据到底是多大…… Posted by:Ruby931031 at 2012-07-09 16:31:42
//我本来假设图是不连通的,对每一个连通分量调用了一下LCA,
//然后改了改,只调用一次LCA,也就是LCA(1),也过了。G++, 266ms
#include <stdio.h>
#include <string.h>
#define MAXN 100000
#define MAXQ 40010
struct Edge{
	int to,len,next,lca;
};

Edge edge[MAXN],qedge[MAXQ];
bool visit[MAXN];
int n,m,head[MAXN],qhead[MAXN],dist[MAXN],p[MAXN];//dist[i]为i到根节点的距离

int find(int x){
	if (x!=p[x])	p[x]=find(p[x]);
	return p[x];
}

void LCA(int u){
	int k;
	p[u]=u;
	visit[u] = true;
	for (k=head[u]; k!=-1; k=edge[k].next)
		if (!visit[ edge[k].to ])
		{
			dist[ edge[k].to ] = edge[k].len + dist[u];
			LCA( edge[k].to );
			p[ edge[k].to ] = u;
		}

	for (k=qhead[u]; k!=-1; k=qedge[k].next)
		if (visit[ qedge[k].to ])
		{
			qedge[k].lca = find( qedge[k].to );
			qedge[k^1].lca = qedge[k].lca;
		}
}

int main()
{
	char ch;
	int tot=0,i,k,len,s,e,query,qx,qy,nroot;
	scanf("%d %d", &n,&m);
	memset(head,-1,sizeof(head));
	for (i=0; i<m; ++i)
	{
		scanf("%d %d %d %c", &s, &e, &len, &ch);
		edge[tot].to = e;		//每条边正反存两遍
		edge[tot].len = len;
		edge[tot].next = head[s];
		head[s] = tot++;

		edge[tot].to = s;
		edge[tot].len = len;
		edge[tot].next = head[e];
		head[e] = tot++;
	}

	scanf("%d", &query);
	memset(qhead,-1,sizeof(qhead));
	for (tot=i=0; i<query; ++i)
	{
		scanf("%d %d", &qx, &qy);
		if (qx==qy)			//两点相同时特殊处理
		{
			qedge[tot].lca = qedge[tot^1].lca = qx;
			qedge[tot].to = qedge[tot^1].to = qx;
			tot+=2;
			continue;
		}
		
		qedge[tot].to = qy;		//存两遍,只对一遍做出应答
		qedge[tot].next = qhead[qx];
		qhead[qx] = tot++;

		qedge[tot].to = qx;
		qedge[tot].next = qhead[qy];
		qhead[qy] = tot++;
	}

	memset(visit,0,sizeof(visit));
	memset(dist,0,sizeof(dist));
	LCA(1);
	for (k=0; k<(query<<1); k+=2)
		printf("%d\n", dist[qedge[k].to] + dist[qedge[k^1].to] - 2 * dist[qedge[k].lca]);
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator