题解:P6606 [Code+#7] 最小路径串
思路
这是一道 DFS 的题,我们把题中的超长数字串转换成边和点的信息,由于它需要字典序最小的路径,我们把每个点所连向的点的编号从小到大进行排序,然后使用数组来记录该点是否被更新过,第一个没有被更新过的点一定是当前答案的最优解。
记得判自环。
AC 代码
#include<bits/stdc++.h>
#define debug(a) cout<<#a<<"="<<a<<'\n';
#define il inline
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int maxm = 1e6+10;
const int MOD = 998244353;
#define int long long
int n,m,a[maxm],b[maxm],ans[maxm];
char c;
vector<int> g[maxm];
void dfs(int u){
for (auto v : g[u]){
if (ans[v] != -1) continue;
ans[v] = (ans[u] * 1000000 + v) % MOD;
dfs(v);
}
}
signed main(){
// freopen("text.in","r",stdin);
// freopen("text.out","w",stdout);
ios::sync_with_stdio(0),cout.tie(0),cin.tie(0);
cin>>n>>m;
for(int i = 1;i <= m;i++){
for(int j = 1;j <= 6;j++){
cin>>c;
a[i] = a[i]*10 + c - 48;
}
for(int j = 1;j <= 6;j++){
cin>>c;
b[i] = b[i]*10 + c - 48;
}
if(a[i] == b[i])continue;
g[a[i]].push_back(b[i]);
g[b[i]].push_back(a[i]);
}
for(int i = 0;i < n;i++)sort(g[i].begin(),g[i].end());
memset(ans,-1,sizeof(ans));
ans[0] = 0;
dfs(0);
for (int i = 1; i < n; i++)cout<<ans[i]<<'\n';
return 0;
}

浙公网安备 33010602011771号