跳到正文

题解

题解 P5764 【[CQOI2005]新年好】

gyh20约 5 分钟
原文
文章信息与版本

文章信息

发布
2019年12月8日
收录
2026年6月14日
更新
2026年11月18日
篇幅
约 5 分钟
题目
P5764

版本

  1. v1当前

本题目标其实就是求一条经过a,b,c,d,e的最短路

在之前我们做过一些类似的题,比如求一条经过某一条连接a,b的路径的最短路,假设起点是s,终点是t,我们求的就是min(dis(s,a)+dis(b,t),dis(s,b),dis(a,t))+w(a,b)

本题大题思路一样,但是需要枚举经过a,b,c,d,e的顺序。

我这里用的是5!的做法,但可以优化至2^5(状态压缩)

剩下的就是裸的最短路了

代码如下(不敢用SPFA,因为它死了):

C++
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#include<cstdio>
#include<queue>
#define re register
#define in inline
#define ll int
using namespace std;
char rbuf[2000002];
int pt;
in char gc(){
    return rbuf[pt++];
}
in int read(){
    re int t=0;
    re char v=gc();
    while(v<'0'||v>'9')v=gc();
    while(v>='0'&&v<='9'){
        t=(t<<3)+(t<<1)+(v^48);
        v=gc();
    }
    return t;
}
struct edge{
    int to,next,w;
}e[200002];
int n,m,cnt,k,l[15],r[15],head[200002],a,b,c,pl[32],w[15];
int d[32][50005],ans,ds[32];
bool vis[15];
struct node{
    int pos;
    int dis;
    bool operator <(const node x)const{
        return dis>x.dis;
    }
}h[50002];
priority_queue <node> q;
bool v[50005];
inline ll M(re ll x,re ll y){
    return (x<y)?(x):(y);
}
inline void dis(re int p,re int s){
    for(re int i=1;i<=n;++i)h[i].dis=1e18;
    h[s].dis=0;
    q.push(h[s]);
    while(!q.empty()){
        while((h[q.top().pos].dis<q.top().dis)){q.pop();if(q.empty())break;
        }
        if(q.empty())break;
        node tmp=q.top();
        q.pop();
        d[p][tmp.pos]=tmp.dis;
        for(re int i=head[tmp.pos];i;i=e[i].next){
            if((tmp.dis+e[i].w)<h[e[i].to].dis){
                h[e[i].to].dis=tmp.dis+e[i].w;
                q.push(h[e[i].to]);
            }
        }
     }
}
inline void find(re int x){
    if(x==k+1){
	ds[1]=d[pl[1]][1];
        for(re int i=2;i<=k;++i){
        	
        	ds[i]=ds[i-1]+d[pl[i-1]][l[pl[i]]];
        	//cout<<pl[i-1]<<" "<<l[pl[i-1]]<<" "<<d[pl[i-1]][l[pl[i-1]]]<<endl;
		}
		ans=M(ans,ds[k]);
        return;
    }
    for(re int i=1;i<=k;++i){
        if(!vis[i]){
            vis[i]=1;
            pl[x]=i;
            find(x+1);
            vis[i]=0;
        }
    }
}
inline void bu(re int x,re int y,re int z){
    e[++cnt].to=y;
    e[cnt].w=z;
    e[cnt].next=head[x];
    head[x]=cnt;
}
signed main(){
//  freopen("test.in","r",stdin);
//  freopen("test.out","w",stdout);
  fread(rbuf,1,2000000,stdin);
    n=read();
    m=read();
    k=5;
    ans=1e9;
    for(re int i=1;i<=n;++i)h[i].pos=i;
    for(re int i=1;i<=5;++i)l[i]=read();
    for(re int i=1;i<=m;++i){//cout<<i<<endl;
        a=read();
        b=read();
        c=read();
        bu(a,b,c);
        bu(b,a,c);
    }
    for(re int i=1;i<=k;++i){
        dis(i,l[i]);
    }
    find(1);
    printf("%d",ans);
}
原文