[P4366][Code+#4]最短路
题目
点这里看题目。
分析
暴力建边肯定不行。而在算法上......好像也没什么可行的特殊算法......
一筹莫展的你沉思了一阵,突然,你抬起了头,惊喜地大叫:“出题人你出锅了边中有无用的!”
显然,如果两个数在二进制上有超过一处的不同处,那么我们就可以用经过多条边代替直接走到,并且花费不变。
比如,从
首先转化为二进制:
尝试通过一位一位地让走到目标节点:
总计
而如果直接从
按照这种方法,边的数量直接就从
代码
#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;
}