This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize ("Ofast")
#define sze(x) (int)(x.size())
typedef long long ll;
typedef pair<ll , ll> pll;
typedef pair<int , int> pii;
const ll maxn = (1 << 20) + 17 , inf = 2e8;
int n , s , t;
vector<pii> adj[maxn];
int dis[22][maxn];
int bfs[maxn] , sz = 0;
int g[maxn] , k[22] , d[22] , e[22] , f[22][22] , dp[maxn][22];
void BFS(int r , int h , bool f = false){
sz = 0;
dis[h][r] = 0;
g[r] = 0;
bfs[sz++] = r;
int x = 0;
while(x < sz){
int v = bfs[x++];
for(auto p : adj[v]){
int i = p.first , t = p.second;
if(dis[h][i] < dis[h][v] + 1) continue;
if(f){
g[i] = g[v];
if(t != -1){
g[i] ^= (1 << t);
d[t] = v;
}
}
dis[h][i] = dis[h][v] + 1;
bfs[sz++] = i;
}
}
return;
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
memset(dp , 63 , sizeof(dp));
memset(dis , 63 , sizeof(dis));
cin>>n>>s>>t; s--; t--;
int m = 0;
for(int i = 1 ; i < n ; i++){
int v , u , w;
cin>>v>>u>>w; v--; u--; w--;
if(w != -1){
k[m] = w;
adj[v].push_back({u , m}); adj[u].push_back({v , m});
m++;
} else {
adj[v].push_back({u , w}); adj[u].push_back({v , w});
}
}
BFS(s , m , true);
if(g[t] == 0){
cout<<dis[m][t]<<'\n';
return 0;
}
for(int j = 0 ; j < m ; j++){
e[j] = g[k[j]] | g[d[j]];
BFS(d[j] , j);
if(e[j] == 0){
dp[(1 << j)][j] = dis[m][k[j]] + dis[j][k[j]];
}
}
for(int i = 0 ; i < m ; i++){
for(int j = 0 ; j < m ; j++){
f[i][j] = dis[i][k[j]] + dis[j][k[j]];
}
}
int lm = (1 << m);
for(int mask = 1 ; mask < lm ; mask++){
for(int j = 0 ; j < m ; j++){
if(mask & (1 << j)) continue;
if((e[j] & mask) != e[j]) continue;
int h = inf;
for(int i = 0 ; i < m ; i++){
if(!(mask & (1 << i))) continue;
h = min(h , dp[mask][i] + f[i][j]);
}
dp[mask ^ (1 << j)][j] = min(dp[mask ^ (1 << j)][j] , h);
}
}
int ans = inf;
for(int mask = 1 ; mask < lm ; mask++){
if((g[t] & mask) != g[t]) continue;
int h = inf;
for(int i = 0 ; i < m ; i++){
if(!(mask & (1 << i))) continue;
// cout<<mask<<' '<<i<<'\n';
h = min(h , dp[mask][i] + dis[i][t]);
}
ans = min(ans , h);
}
cout<<(ans == inf ? -1 : ans)<<'\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |