#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define vi vector<int>
#define vll vector<ll>
#define vvi vector<vector<int>>
#define all(x) (x).begin(),(x).end()
#define rep(i, n) for (int i = 0; i < n; i++)
#define Rep(i, n) for (int i = 1; i <= n; i++)
typedef pair<int, int> P;

const ll INF = 1ll<<60;
typedef struct{int to, cost;} edge;
int N, Q, K;
vector<edge> G[100100];
vll d(100100, INF);

void nya(int s){
    priority_queue<P, vector<P>, greater<P> >que;
    d[s] = 0ll;
    que.push(P(0, s));
    while(!que.empty()){
        P p = que.top(); que.pop();
        int v = p.second;
        if(d[v] < p.first) continue;
        rep(i, G[v].size()){
            edge e = G[v][i];
            if(d[e.to] > d[v] + e.cost){
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to], e.to));
            }
        }
    }
    return;
}

int main(){
    cin >> N;
    rep(i, N)if(i){
        int a, b, c;
        cin >> a >> b >> c;
        a--; b--;
        edge tmp;
        tmp.to = b;
        tmp.cost = c;
        G[a].push_back(tmp);
        tmp.to = a;
        G[b].push_back(tmp);
    }
    cin >> Q >> K;
    nya(K - 1);
    while(Q--){
        int x, y;
        cin >> x >> y;
        x--; y--;
        cout << d[x] + d[y] << endl;
    }
    return 0;
}
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
 
using namespace __gnu_pbds;
using namespace std;
 
typedef long long int ll;
typedef unsigned long long int sll;
typedef  double ld;
#define A 1000000007ll
#define D 1000000000ll
#define B 998244353ll
#define C 1000000000000000000ll
#define FAST ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define oset tree<pair<ll,ll>, null_type,less<pair<ll,ll>>, rb_tree_tag,tree_order_statistics_node_update> 
#define pb push_back
#define puf push_front
#define pob pop_back
#define pof pop_front
#define mxe(v) *max_element(v.begin(),v.end())
#define mne(v) *min_element(v.begin(),v.end())
#define bs binary_search
#define lb lower_bound
#define ub upper_bound
#define ve vector
#define br break
#define PI 3.14159265358979323
#define subt cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n"

ll dp[7007];

int main() 
{
    FAST;
    ll n,t;
    cin>>n>>t;
    pair<ll,ll> a[n];
    ll x,y;
    for(int i=0;i<n;i++)
    {
        cin>>x>>y;
        a[i]={x,y};
    }
    sort(a,a+n);
    for(int i=1;i<7007;i++)
        dp[i]=-1;
    for(int i=0;i<n;i++)
        for(int j=t-1;j>=0;j--)
            if(dp[j]!=-1)
                dp[a[i].first+j]=max(dp[a[i].first+j],dp[j]+a[i].second);
    ll ans=0;
    for(int i=0;i<7007;i++)
        ans=max(ans,dp[i]);
    cout<<ans;
    subt;   
    return 0;
}