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

Dij+堆优化 附代码代码比较乱

Posted by luoxuqing at 2017-08-10 10:41:56 on Problem 1206
更新rank【i】为结点的离他距离最近的rank>j的节点的距离
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <queue>
using namespace std;
struct ff
{
	int nx,y,d;
} e[300010];
int dist[30010],rank[30010],Head[30010],TopR;
int B[12][30010];

struct xgd
{
	int y;
	bool operator < (const xgd &b) const
	{
		return dist[y]>dist[b.y];
	}
} tmp,now;
priority_queue<xgd>q;
int n,m,tot=0;
bool vis[30010];

inline void Add(int a,int b,int c)
{
	tot++;
	e[tot].y=b;
	e[tot].d=c;
	e[tot].nx=Head[a];
	Head[a]=tot;
	tot++;
	e[tot].y=a;
	e[tot].d=c;
	e[tot].nx=Head[b];
	Head[b]=tot;
}

void csh()
{
	int l,r,y;
	for(int i=1; i<=9; i++)
		for(int j=1; j<=9; j++) B[i][j]=100000000;

	for(int i=1; i<=9; i++)
	{
		l=1;
		r=0;
		memset(vis,0,sizeof(vis));
		while(!q.empty()) q.pop();
		for(int j=1; j<=n; j++) dist[j]=100000000;
		for(int j=1; j<=n; j++)
			if(rank[j]>i)
			{
				tmp.y=j;
				q.push(tmp);
				r++;
				dist[j]=0;
			}
		while(l<=r)
		{
			now=q.top();
			q.pop();
			B[i][now.y]=dist[now.y];
			for(int k=Head[now.y]; k; k=e[k].nx)
			{
				y=dist[now.y]+e[k].d;
				if(y<dist[e[k].y])
				{
					dist[e[k].y]=y;
					if(!vis[e[k].y])
					{
						tmp.y=e[k].y;
						q.push(tmp);
						r++;
						vis[e[k].y]=1;
					}
				}
			}
			l++;
		}
	}
}

int Dij(int v)
{
	int halo,res,y;
	if (rank[v]==TopR) return n;
	int l=1,r=1;
	res=0;
	halo=rank[v];
	memset(vis,0,sizeof(vis));
	while(!q.empty()) q.pop();
	for(int j=1;j<=n;j++) dist[j]=100000000;
	tmp.y=v;
	dist[v]=0;
	q.push(tmp);
	vis[v]=1;
	rank[v]=0;
	while(l<=r)
	{
		now=q.top();
		q.pop();
		if(dist[now.y]<B[halo][now.y])
		{
			res++;
			for(int i=Head[now.y];i;i=e[i].nx)
			{
				y=dist[now.y]+e[i].d;
				if (y<dist[e[i].y])
				{
					dist[e[i].y]=y;
					if (!vis[e[i].y])
					{
						tmp.y=e[i].y;
						q.push(tmp);
						r++;
						vis[e[i].y]=1;
					}
				}
			}
		}
		l++;
	}
	return res;
}

int main()
{
//	freopen("servers.in","r",stdin);
//	freopen("servers.out","w",stdout);
	scanf("%d%d",&n,&m);
	TopR=0;
	for(int i=1; i<=n; i++)
	{
		scanf("%d",&rank[i]);
		if(rank[i]>TopR) TopR=rank[i];
	}
	int x,y,p;
	for(int i=1; i<=m; i++)
	{
		scanf("%d%d%d",&x,&y,&p);
		Add(x,y,p);
	}
	csh();
	int ans=0;
	for(int i=1; i<=n; i++) ans+=Dij(i);
	printf("%d\n",ans);
//	fclose(stdin);
//	fclose(stdout);
	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