跳到正文

题解

[P4366][Code+#4]最短路

crashed约 7 分钟
原文
文章信息与版本

文章信息

发布
2019年8月6日
收录
2026年2月2日
更新
2026年11月14日
篇幅
约 7 分钟
题目
P4366

版本

  1. v2当前
  2. v1

题目

        点这里看题目。

分析

        暴力建边肯定不行。而在算法上…好像也没什么可行的特殊算法…         一筹莫展的你沉思了一阵,突然,你抬起了头,惊喜地大叫:“出题人你出锅了边中有无用的!”         Exactly!Exactly!         显然,如果两个数在二进制上有超过一处的不同处,那么我们就可以用经过多条边代替直接走到,并且花费不变。         比如,从11走到66:         首先转化为二进制:(001)2(001)_2和(110)2(110)_2         尝试通过一位一位地让走到目标节点:         (001)2→(101)2(001)_2\rightarrow (101)_2,花费4C4C         (101)2→(100)2(101)_2\rightarrow (100)_2,花费CC         (100)2→(110)2(100)_2\rightarrow (110)_2,花费2C2C         总计7C7C。         而如果直接从11走到66的话,花费也是7C7C。         按照这种方法,边的数量直接就从O(n2)O(n^2)降成了O(n×log2(N))O(n\times log_2(N))。然后再新的图上跑DijkstraDijkstra就可以了。

代码

C++
#include <cmath>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;

const int MAXN = 1e5 + 5, MAXM = 5e5 + 5, MAXLOG = 17;

template<typename _T>
void read( _T &x )
{
	x = 0;char s = getchar();int f = 1;
	while( s > '9' || s < '0' ){if( s == '-' ) f = -1; s = getchar();}
	while( s >= '0' && s <= '9' ){x = ( x << 3 ) + ( x << 1 ) + ( s - '0' ), s = getchar();}
	x *= f;
}

template<typename _T>
void write( _T x )
{
	if( x < 0 ){ putchar( '-' ); x = ( ~ x ) + 1; }
	if( 9 < x ){ write( x / 10 ); }
	putchar( x % 10 + '0' );
}

struct edge
{
	int to, nxt, w;
}Graph[MAXN * MAXLOG * 4 + MAXM];

struct node
{
	int u, dis;
	node(){}
	node( const int U, const int Dis )
	{
		u = U, dis = Dis;
	}
	bool operator < ( const node & other ) const
	{
		return ! ( dis < other.dis );
	}
};

priority_queue<node> q;

int dis[2 * MAXN];
int head[2 * MAXN];
int N, M, A, B, C, cnt, lg2;
bool visited[2 * MAXN];

void addEdge( const int from, const int to, const int W )
{
	cnt ++;
	Graph[cnt].nxt = head[from];
	Graph[cnt].to = to;
	Graph[cnt].w = W;
	head[from] = cnt;
}

int Dijkstra( const int sta, const int tar )
{
	while( ! q.empty() ) q.pop();
	memset( dis, 0x3f, sizeof( dis ) );
	memset( visited, false, sizeof( visited ) );
	dis[sta] = 0;
	q.push( node( sta, 0 ) );
	node h;
	int v, w;
	while( ! q.empty() )
	{
		h = q.top();
		q.pop();
		if( visited[h.u] ) continue;
		if( h.u == tar ) return h.dis;
		visited[h.u] = true;
		for( int i = head[h.u] ; i ; i = Graph[i].nxt )
		{
			v = Graph[i].to, w = Graph[i].w;
			if( ! visited[v] )
			{
				if( dis[v] > dis[h.u] + w )
				{
					dis[v] = dis[h.u] + w;
					q.push( node( v, dis[v] ) );
				}
			}
		}
	}
	return -1;
}

int main()
{
	int fr, to, W;
	read( N ), read( M ), read( C );
	lg2 = log2( N );
	for( int i = 1 ; i <= M ; i ++ )
	{
		read( fr ), read( to ), read( W );
		addEdge( fr, to, W );
	}
	for( int i = 1 ; i <= N + ( 1 << lg2 ) ; i ++ )
	{
		for( int j = 0 ; j <= lg2 ; j ++ )
		{
			to = i ^ ( 1 << j );
			addEdge( i, to, ( 1 << j ) * C );
		}
	}
	read( A ), read( B );
	write( Dijkstra( A, B ) ), putchar( '\n' );
	return 0;
}
原文
存档评论1 条抓取于