bool debug=false;
#include <stdio.h>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
#define PB push_back
#define F first
#define S second
const int N=6e3+10;
const int INF=1e9+10;
vector<pair<int,int>> graph[N];
int in[N],from[N],a[N],p[N],s[N],went[N];
int run(int root,int v){
	if(root+1==v)return 0;
	if(debug){
		printf("run(%d,%d)\n",root,v);
		for(int i=root;i<v;i++)for(pair<int,int> j:graph[i])printf("%d to %d cost=%d\n",i,j.F,j.S);
		printf("done debug\n");
	}
	int now,ans=0,tt,nv=v+1;
	for(int i=root;i<v;i++)from[i]=-1,in[i]=INF,went[i]=0;
	for(int i=root;i<v;i++)for(pair<int,int> j:graph[i])if(in[j.F]>j.S){
		from[j.F]=i;
		in[j.F]=j.S;
	}
	for(int i=root+1;i<v;i++)if(from[i]==-1)return -INF;
	else ans+=in[i];
	graph[v].clear();
	for(int i=root;i<v;i++)p[i]=v;
	went[root]=-2;
	for(int i=root+1;i<v;i++)if(went[i]==0){
		if(debug)printf("i=%d::\n",i);
		now=i;
		while(went[now]==0){
			if(debug)printf("dfs %d\n",now);
			went[now]=-1;
			now=from[now];
		}
		if(went[now]==-1){
			tt=now;
			now=i;
			while(now!=tt){
				went[now]=-4;
				now=from[now];
			}
			if(debug)printf("find ring\nnow=%d\n",now);
			p[now]=nv;
			graph[nv].clear();
			went[now]=-3;
			now=from[now];
			while(now!=tt){
				p[now]=nv;
				went[now]=-3;
				if(debug)printf("p[now=%d]=%d\n",now,p[now]);
				now=from[now];
			}
			nv++;
		}
		if(went[now]==-2){
			now=i;
			while(went[now]==-1){
				went[now]=-2;
				now=from[now];
			}
		}
		else {
			now=i;
			while(went[now]==-1){
				went[now]=-4;
				now=from[now];
			}
		}
	}
	for(int i=root;i<v;i++)if(went[i]!=-2&&p[i]==v)p[i]=nv++;
	if(debug)for(int i=root;i<v;i++)printf("p[%d]=%d\n",i,p[i]);
	if(debug)for(int i=root;i<v;i++)printf("went[%d]=%d\n",i,went[i]);
	for(int i=root;i<v;i++)for(pair<int,int> j:graph[i])if(p[j.F]!=p[i]&&went[j.F]!=-2)graph[p[i]].PB({p[j.F],j.S-in[j.F]});
	ans+=run(v,nv);
	return ans;
}
void solve(int n,int m,int root){
	int ans,l,r,x,y,c;
	for(int i=0;i<n;i++)graph[i].clear();
	while(m--){
	    scanf("%d%d%d",&l,&r,&c);
	    if(r==root)continue;
	    else if(l==root)graph[0].PB({r==0?root:r,c});
	    else graph[l==0?root:l].PB({r==0?root:r,c});
	}
	ans=run(0,n);
	if(ans<0)printf("-1\n");
	else printf("%d\n",ans);
}
int main(){
    int n,m,r;
    scanf("%d%d%d",&n,&m,&r);
	solve(n,m,r);
}

