P5304 [GXOI/GZOI2019]旅行者(奇妙建图+二进制枚举)
题意
一个图 点 条有向边,里面有 个特殊点,问这 个点之间两两最短路的最小值是多少?
数据范围
,
思路
假设我们把特殊点分成 两个集合,新建 连 集合的所有点,边权 ,新建 连接 集合里的所有点,边权 ,那么 到 的最短路就是 集合点之间的最短路的最小值。
那么对于 个特殊点,我们枚举二进制里的第 位,把二进制第 位是 的点放在 , 的点放在 ,用以上方法跑两个最短路(正反都需要跑)。
然后跑 次最短路之后,所有最短路的最小值就是最终答案。
原理是,假设 个特殊点里最近的是 和 ,那么 和 一定有一个二进制位不一样,那么他们肯定在那次分组的时候被放进了不同的集合,从而肯定被算进了最后的答案之中最短路。
code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
//#pragma GCC optimize(3)
#define pb push_back
#define is insert
#define PII pair<int,int>
#define show(x) cerr<<#x<<" : "<<x<<endl;
//mt19937 mt19937random(std::chrono::system_clock::now().time_since_epoch().count());
//ll getRandom(ll l,ll r){return uniform_int_distribution<ll>(l,r)(mt19937random);}
const ll INF=0x3f3f3f3f;//2147483647;
const int N=1e5+50;
const ll mod=998244353;
int n,m,k;
vector<PII>to[N];
vector<PII>tmp[N];
int a[N];
int S=0,T;
int d[N];
int vis[N];
void dijkstra(){
memset(d,INF,sizeof d);
memset(vis,0,sizeof vis);
d[S]=0;
priority_queue<PII,vector<PII>,greater<PII>>q;
q.push({d[S],S});
while(!q.empty()){
// for(int j=0;j<=n+1;j++){
// cout<<d[j]<<" ";
// }cout<<endl;
PII now=q.top();q.pop();
int u=now.second;
// cout<<"u="<<u<<endl;
if(vis[u])continue;
vis[u]=1;
for(auto i:to[u]){
int v=i.first,val=i.second;
// cout<<v<<" "<<val<<endl;
if(d[v]>d[u]+val){
d[v]=d[u]+val;
if(!vis[v])q.push({d[v],v});
}
}
}
}
void solve() {
cin>>n>>m>>k;T=n+1;
for(int i=1;i<=m;i++){
int u,v,val;cin>>u>>v>>val;
tmp[u].pb({v,val});
}
for(int i=1;i<=k;i++){
cin>>a[i];
}
int ans=INF;
for(int i=0;i<17;i++){
for(int j=0;j<=n+1;j++){
to[j].clear();
to[j]=tmp[j];
}
vector<int>A,B;
for(int j=1;j<=k;j++){
if((1<<i)&a[j]){
to[S].pb({a[j],0});
A.pb(a[j]);
}
else {
to[a[j]].pb({T,0});
B.pb(a[j]);
}
}
dijkstra();
ans=min(ans,d[T]);
}
for(int i=0;i<17;i++){
for(int j=0;j<=n+1;j++){
to[j].clear();
to[j]=tmp[j];
}
vector<int>A,B;
for(int j=1;j<=k;j++){
if(((1<<i)&a[j])==0){
to[S].pb({a[j],0});
A.pb(a[j]);
}
else {
to[a[j]].pb({T,0});
B.pb(a[j]);
}
}
dijkstra();
ans=min(ans,d[T]);
}
cout<<ans<<"\n";
for(int i=0;i<=n+1;i++){
tmp[i].clear();
}
}
signed main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int __=1;cin>>__;
while(__--){
solve();
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下