/** made by amunduzbaev **/
#include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define ub upper_bound
#define lb lower_bound
#define ll long long
#define ld long double
#define pii pair<int, int>
#define pll pair<ll, ll>
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(),x.rend()
#define fastios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define vll vector<ll>
#define vii vector<int>
#define vpii vector<pii>
#define vpll vector<pll>
#define cnt(a)__builtin_popcount(a)
const int N = 2e5+5;
const int mod = 1e9+7;
const ll inf = 1e18;
const ld Pi = acos(-1);
ll n, m, k, ans, pp[N], used[N], a[N];
vll edgess[N];
bool dfsp(int u){
if(pp[u] == u) return 0;
if(used[pp[u]])return 1;
return dfsp(pp[u]);
}
bool dfss(int u){
bool ok = 0;
for(auto x:edgess[u]){
if(used[x]) return 1;
ok |= dfss(x);
}return ok;
}
void solve(){
fastios
cin>>n>>m;
for(int i=1;i<=n;i++){
ll x, mem;
cin>>x>>mem;
pp[i] = x;
edgess[x].pb(i);
a[i] = mem;
}
for(int i=0;i<(1<<n);i++){
if(__builtin_popcount(i) != m) continue;
memset(used, 0, sizeof used);
bool ok = 1;
for(int j=0;j<n;j++) if(i & (1<<j)) used[j+1] = 1;
for(int j=0;j<n && ok;j++) if(used[j+1]) if(dfsp(j+1) || dfss(j+1)) ok = 0;
if(ok){
ll tmpans = 0;
for(int j=0;j<n;j++) if(used[j+1]) tmpans += a[j+1];
ans = max(ans, tmpans);
}
}cout<<ans<<endl;
return;
}
int main(){
fastios
int t = 1;
if(t) solve();
else {
cin>>t;
while (t--) solve();
}
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
11 ms |
6636 KB |
Output is correct |
2 |
Correct |
7 ms |
6636 KB |
Output is correct |
3 |
Incorrect |
3 ms |
5100 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |