alg2025/src/11/13/P7297.cpp
Zengtudor 71bb5fe79f feat: 添加两个算法题目解决方案
添加P8187.cpp和P7297.cpp两个算法题目的解决方案代码。P8187实现了一个简单的点比较算法,P7297实现了一个基于优先队列的图搜索算法。
2025-11-13 13:28:41 +08:00

69 lines
1.6 KiB
C++

#include <algorithm>
#include <bitset>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <istream>
#include <queue>
#include <vector>
using ll = int;
const ll maxn=5e4+5,maxk=51,inf=1e9+7;
ll n,k,b[maxn];
std::vector<std::vector<int>> edg;
std::vector<std::vector<int>> classp;
ll vis[maxn];
struct P{
ll now,step;
inline bool operator<(const P&o)const{
return step>o.step;
}
};
#define printf
int main(){
std::iostream::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cin>>n>>k;
edg.resize(k+1);
classp.resize(k+1);
for(ll i=1;i<=n;i++){
std::cin>>b[i];
classp[b[i]].emplace_back(i);
vis[i]=inf;
}
for(ll i=1;i<=k;i++){
for(ll j=1;j<=k;j++){
char tmp;
std::cin>>tmp;
if(tmp=='1'){
edg[i].emplace_back(j);
}
}
}
std::priority_queue<P> pq;
pq.emplace(1,0);
while(pq.size()){
auto[now,step]=pq.top();
pq.pop();
if(vis[now]!=inf)continue;
vis[now]=std::min(step,vis[now]);
printf("dij now=%lld, step=%lld\n",now,step);
if(now==n){
std::cout<<step<<"\n";
return 0;
}
for(ll i:edg[b[now]]){
for(ll p:classp[i]){
if(p==now)continue;
printf("%lld goto %lld\n",b[now],i);
ll nstep=step+std::abs(p-now);
if(nstep>vis[p])continue;
pq.emplace(p,step+std::abs(p-now));
}
}
}
std::cout<<"-1\n";
}