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("O3,unroll-loops")
// #pragma GCC optimize("avx2")
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define pb push_back
#define int long long
#define S second
#define F first
#define mp make_pair
#define smax(xyxy, yxy) (xyxy) = max((xyxy), (yxy))
#define smin(xyxy, yxy) (xyxy) = min((xyxy), (yxy))
#define all(xyxy) (xyxy).begin(), (xyxy).end()
#define len(xyxy) ((int)(xyxy).size())
const int maxn = 2e6 + 5, lg = 22;
const ll inf = 1e15 + 7;
ll n, s, t, w[lg], dp[(1ll << lg)][lg + 1];
pll d[lg + 1][maxn];
vector<pll> adj[maxn];
pll a[lg];
void dfs(int v, int p, int id){
for(auto [u, e]: adj[v]){
if(u == p) continue;
d[id][u].F = d[id][v].F + 1;
d[id][u].S = d[id][v].S;
if(e != -1) d[id][u].S += 1ll << e;
dfs(u, v, id);
}
}
int32_t main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> s >> t;
int m = 0;
for(int i = 0; i < n - 1; i++){
int u, v, we; cin >> u >> v >> we;
if(we == 0){
adj[u].pb(mp(v, -1));
adj[v].pb(mp(u, -1));
}
else{
a[m] = mp(u, v);
adj[u].pb(mp(v, m));
adj[v].pb(mp(u, m));
w[m] = we;
m++;
}
}
dfs(s, 0, m);
for(int i = 0; i < m; i++){
int v = a[i].F;
if(d[m][a[i].S].F < d[m][a[i].F].F) v = a[i].S;
dfs(v, 0, i);
}
for(int mask = (1ll << m) - 1; mask >= 0; mask--){
for(int i = 0; i <= m; i++){
dp[mask][i] = inf;
int m1 = d[i][t].S, h = d[i][t].F;
if((m1 & mask) == m1){
dp[mask][i] = d[i][t].F;
continue;
}
for(int j = 0; j < m; j++){
if(mask & (1ll << j)) continue;
int res = d[i][w[j]].F;
int m2 = d[i][w[j]].S;
if((m2 & mask) == m2){
int m3 = d[j][w[j]].S;
res += d[j][w[j]].F + dp[mask + (1ll << j)][j];
if((m3 & (mask + (1ll << j))) == m3) smin(dp[mask][i], res);
}
}
}
}
if(dp[0][m] >= inf) cout << -1 << '\n';
else cout << dp[0][m] << '\n';
return 0;
}
Compilation message (stderr)
Main.cpp: In function 'int32_t main()':
Main.cpp:67:33: warning: unused variable 'h' [-Wunused-variable]
67 | int m1 = d[i][t].S, h = d[i][t].F;
| ^
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |