#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;
int c,wayto[200010],waycost[200010];
bool used[200010],usedt[200010],usedtt[200010];
long long goin(int pos)
{
memset(usedtt,0,sizeof(usedtt));
long long cost=0;
while (pos)
{
if (used[pos]||usedtt[pos])
break;
usedt[pos]=true;
usedtt[pos]=true;
cost+=waycost[pos];
pos=wayto[pos];
}
return(cost);
}
void use(int pos)
{
while (pos&&!used[pos])
{
c--;
used[pos]=true;
pos=wayto[pos];
}
}
int main(void)
{
freopen("bombb.in","r",stdin);
freopen("bombb.out","w",stdout);
int i,n,k,it;
long long cost,maxcost,total=0;
cin>>n>>k;
c=n;
for (i=1;i<=n;i++)
cin>>wayto[i]>>waycost[i];
while (k>0&&c>0)
{
k--;
maxcost=0;
memset(usedt,0,sizeof(usedt));
for (i=1;i<=n;i++)
{
if (used[i])
continue;
if (usedt[i])
continue;
cost=goin(i);
if (maxcost<cost)
{
maxcost=cost;
it=i;
}
}
total+=maxcost;
use(it);
}
cout<<total<<endl;
return(0);
}