#include <bits/stdc++.h>
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))

namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
	bool IOerror=0;
	inline char nc() {
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend) {
			p1=buf;
			pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1) {
				IOerror=1;
				return -1;
			}
		}
		return *p1++;
	}
	inline bool blank(char ch) {
		return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
	}
	template<class T> inline bool read(T &x) {
		bool sign=0;
		char ch=nc();
		x=0;
		for(; blank(ch); ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	template<class T,class... U>bool read(T& h,U&... t) {
		return read(h)&&read(t...);
	}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int INF = 0x3f3f3f3f;
const int N = 1e6+10;

vector<int>e[N];
int siz[N],dep[N],son[N],ans[N],sum[N];

void dfs1(int u,int fa) {
	dep[u]=dep[fa]+1;
	siz[u]=1;
	int maxlen=0;
	for(auto v:e[u]) {
		if(v==fa) continue;
		dfs1(v,u);
		siz[u]+=siz[v];
		if(siz[v]>siz[son[u]]) son[u]=v;
	}
}

int ma,res;

void add(int u,int fa) {
	sum[dep[u]]++;
	if(sum[dep[u]]>ma){
		ma=sum[dep[u]];
		res=dep[u];
	}
	for(auto v:e[u]) if(v!=fa) add(v,u);
}

void del(int u,int fa) {
	sum[dep[u]]--;
	for(auto v:e[u]) if(v!=fa) del(v,u);
}

void dfs2(int u,int fa) {
	ma=1,res=dep[u];
	sum[dep[u]]++;
	for(auto v:e[u]) {
		if(v==fa || v==son[u]) continue;
		dfs2(v,u);
		del(v,u);
	}
	if(son[u]) dfs2(son[u],u);
	for(auto v:e[u]) {
		if(v==son[u] || v==fa) continue;
		add(v,u);
	}
	ans[u]=res-dep[u];
}

int main() {

#ifdef xiaofan
	freopen("1.in","r",stdin);
	freopen("1.out","w",stdout);
#endif

	int n;
	read(n);
	for(int i=1; i<n; i++) {
		int u,v;
		read(u,v);
		e[u].pb(v);
		e[v].pb(u);
	}
	dfs1(1,0);
	dfs2(1,0);
	for(int i=1; i<=n; i++) printf("%d\n",ans[i]);

	return 0;
}


#include <bits/stdc++.h>
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))

namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
	bool IOerror=0;
	inline char nc() {
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend) {
			p1=buf;
			pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1) {
				IOerror=1;
				return -1;
			}
		}
		return *p1++;
	}
	inline bool blank(char ch) {
		return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
	}
	template<class T> inline bool read(T &x) {
		bool sign=0;
		char ch=nc();
		x=0;
		for(; blank(ch); ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	template<class T,class... U>bool read(T& h,U&... t) {
		return read(h)&&read(t...);
	}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int INF = 0x3f3f3f3f;
const int N = 1e6+10;

vector<int>e[N];
int siz[N],dep[N],son[N],ans[N],sum[N];

void dfs1(int u,int fa) {
	dep[u]=dep[fa]+1;
	siz[u]=1;
	int maxlen=0;
	for(auto v:e[u]) {
		if(v==fa) continue;
		dfs1(v,u);
		siz[u]+=siz[v];
		if(siz[v]>siz[son[u]]) son[u]=v;
	}
}

int ma,res;

void add(int u,int fa) {
	sum[dep[u]]++;
	if(sum[dep[u]]>ma) {
		ma=sum[dep[u]];
		res=dep[u];
	}
	for(auto v:e[u]) if(v!=fa) add(v,u);
}

void del(int u,int fa) {
	sum[dep[u]]--;
	for(auto v:e[u]) if(v!=fa) del(v,u);
}

void dfs2(int u,int fa) {
	for(auto v:e[u]) {
		if(v==fa || v==son[u]) continue;
		dfs2(v,u);
		del(v,u);
	}
	if(son[u]) dfs2(son[u],u);
	ma=1;
	res=dep[u];
	for(auto v:e[u]) {
		if(v==son[u] || v==fa) continue;
		add(v,u);
	}
	ans[u]=res-dep[u];
}

int main() {

#ifdef xiaofan
	freopen("1.in","r",stdin);
	freopen("1.out","w",stdout);
#endif

	int n;
	read(n);
	for(int i=1; i<n; i++) {
		int u,v;
		read(u,v);
		e[u].pb(v);
		e[v].pb(u);
	}
	dfs1(1,0);
	dfs2(1,0);
	for(int i=1; i<=n; i++) printf("%d\n",ans[i]);

	return 0;
}


#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))

namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
	bool IOerror=0;
	inline char nc() {
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend) {
			p1=buf;
			pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1) {
				IOerror=1;
				return -1;
			}
		}
		return *p1++;
	}
	inline bool blank(char ch) {
		return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
	}
	template<class T> inline bool read(T &x) {
		bool sign=0;
		char ch=nc();
		x=0;
		for(; blank(ch); ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	template<class T,class... U>bool read(T& h,U&... t) {
		return read(h)&&read(t...);
	}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int INF = 0x3f3f3f3f;
const int N = 1e6+1;

struct node {
	int ls,rs,ma;
	void clear(){
		ls=0;
		rs=0;
		ma=0;
	}
} tree[N * 10];

int ans[N],dep[N];
int root[N],cnt,st[N*10],top;
vector<int>e[N];

void pp(int x) {
	int ls=tree[x].ls;
	int rs=tree[x].rs;
	tree[x].ma=max(tree[ls].ma,tree[rs].ma);
}

int newnode(){
	if(top) return st[top--];
	else return ++cnt;
}

void ins(int &x,int l,int r,int pos) {
	if(!x) x=newnode();
	if(l==r) {
		tree[x].ma++;
		return ;
	}
	int mid=l+r>>1;
	if(pos<=mid) ins(tree[x].ls,l,mid,pos);
	else ins(tree[x].rs,mid+1,r,pos);
	pp(x);
}

int merge(int x,int y,int l,int r) {
	if( !x || !y) return x?x:y;
	if(l==r) {
		tree[x].ma+=tree[y].ma;
		st[++top]=y;
		tree[y].clear();
		return x;
	}
	int mid=l+r>>1;
	tree[x].ls=merge(tree[x].ls,tree[y].ls,l,mid);
	tree[x].rs=merge(tree[x].rs,tree[y].rs,mid+1,r);
	pp(x);
	tree[y].clear();
	st[++top]=y;
	return x;
}

int query(int x,int l,int r){
	if(l==r) return l;
	int mid=l+r>>1;
	int ls=tree[x].ls;
	int rs=tree[x].rs;
	if(tree[ls].ma>=tree[rs].ma) return query(ls,l,mid);
	else return query(rs,mid+1,r);
}

void dfs(int u,int f) {
	dep[u]=dep[f]+1;
	ins(root[u],1,N,dep[u]);
	for(auto v:e[u]) {
		if(v==f) continue;
		dfs(v,u);
		root[u]=merge(root[u],root[v],1,N);
	}
	ans[u]=query(root[u],1,N)-dep[u];
}

int main() {

#ifdef xiaofan
	freopen("1.in","r",stdin);
	freopen("1.out","w",stdout);
#endif

	int n;
	cin>>n;
	for(int i=1; i<n; i++) {
		int u,v;
		cin>>u>>v;
		e[u].pb(v);
		e[v].pb(u);
	}
	dfs(1,0);
	for(int i=1; i<=n; i++) cout<<ans[i]<<endl;

	return 0;
}


#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))

namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
	bool IOerror=0;
	inline char nc() {
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend) {
			p1=buf;
			pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1) {
				IOerror=1;
				return -1;
			}
		}
		return *p1++;
	}
	inline bool blank(char ch) {
		return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
	}
	template<class T> inline bool read(T &x) {
		bool sign=0;
		char ch=nc();
		x=0;
		for(; blank(ch); ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	template<class T,class... U>bool read(T& h,U&... t) {
		return read(h)&&read(t...);
	}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int INF = 0x3f3f3f3f;
const int N = 1e6+1;

struct node {
	int ls,rs,ma;
} tree[N * 40];

int ans[N],dep[N];
int root[N],cnt,st[N],top;
vector<int>e[N];

void pp(int x) {
	int ls=tree[x].ls;
	int rs=tree[x].rs;
	tree[x].ma=max(tree[ls].ma,tree[rs].ma);
}

int newnode(){
	if(top) return st[top--];
	else return ++cnt;
}

void ins(int &x,int l,int r,int pos) {
	if(!x) x=newnode();
	if(l==r) {
		tree[x].ma++;
		return ;
	}
	int mid=l+r>>1;
	if(pos<=mid) ins(tree[x].ls,l,mid,pos);
	else ins(tree[x].rs,mid+1,r,pos);
	pp(x);
}

int merge(int x,int y,int l,int r) {
	if( !x || !y) return x?x:y;
	if(l==r) {
		tree[x].ma+=tree[y].ma;
		st[++top]=y;
		return x;
	}
	int mid=l+r>>1;
	tree[x].ls=merge(tree[x].ls,tree[y].ls,l,mid);
	tree[x].rs=merge(tree[x].rs,tree[y].rs,mid+1,r);
	pp(x);
	st[++top]=y;
	return x;
}

int query(int x,int l,int r){
	if(l==r) return l;
	int mid=l+r>>1;
	int ls=tree[x].ls;
	int rs=tree[x].rs;
	if(tree[ls].ma>=tree[rs].ma) return query(ls,l,mid);
	else return query(rs,mid+1,r);
}

void dfs(int u,int f) {
	dep[u]=dep[f]+1;
	ins(root[u],1,N,dep[u]);
	for(auto v:e[u]) {
		if(v==f) continue;
		dfs(v,u);
		root[u]=merge(root[u],root[v],1,N);
	}
	ans[u]=query(root[u],1,N)-dep[u];
}

int main() {

#ifdef xiaofan
	freopen("1.in","r",stdin);
	freopen("1.out","w",stdout);
#endif

	int n;
	cin>>n;
	for(int i=1; i<n; i++) {
		int u,v;
		cin>>u>>v;
		e[u].pb(v);
		e[v].pb(u);
	}
	dfs(1,0);
	for(int i=1; i<=n; i++) cout<<ans[i]<<endl;

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
inline int read(){
	int res=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-f;ch=getchar();}
	while(ch>='0'&&ch<='9'){res=(res<<3)+(res<<1)+ch-'0';ch=getchar();}
	return res*f;
}
void write(int x){
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10|'0');
}
const int N=2000005;
const int M=21000005;
int n,fir[N],nxt[N<<1],go[N<<1],dep[N],cnt,CNT;
int root[N],lc[M],rc[M],tr[M],id[M],ans[N];
inline void Add(int u,int v){
	nxt[++cnt]=fir[u];
	fir[u]=cnt;
	go[cnt]=v;
}
void init(int u,int fa){
	dep[u]=dep[fa]+1;
	for(int e=fir[u];e;e=nxt[e]){
		int v=go[e];
		if(v==fa) continue;
		init(v,u);
	}
}
void insert(int &now,int l,int r,int x,int val){
	if(!now) now=++CNT;
	if(l==r){
		tr[now]+=val;
		id[now]=x;
		return ;
	}
	int mid=(l+r)>>1;
	if(x<=mid) insert(lc[now],l,mid,x,val);
	else insert(rc[now],mid+1,r,x,val);
	if(tr[lc[now]]>=tr[rc[now]]){
		tr[now]=tr[lc[now]];
		id[now]=id[lc[now]];
	}else{
		tr[now]=tr[rc[now]];
		id[now]=id[rc[now]];
	}
}
int merge(int x,int y,int l,int r){
	if(!x) return y;
	if(!y) return x;
	if(l==r){
		tr[x]+=tr[y];
		id[x]=l;
		return x;
	}
	int mid=(l+r)>>1;
	lc[x]=merge(lc[x],lc[y],l,mid);
	rc[x]=merge(rc[x],rc[y],mid+1,r);
	if(tr[lc[x]]>=tr[rc[x]]){
		tr[x]=tr[lc[x]];
		id[x]=id[lc[x]];
	}else{
		tr[x]=tr[rc[x]];
		id[x]=id[rc[x]];
	}
	return x;
}
void dfs(int u,int fa){
	insert(root[u],1,n,dep[u],1);
	for(int e=fir[u];e;e=nxt[e]){
		int v=go[e];
		if(v==fa) continue;
		dfs(v,u);
		root[u]=merge(root[u],root[v],1,n);
	}
	ans[u]=id[root[u]]-dep[u];
}
int main(){
	n=read();
	for(int i=1;i<n;i++){
		int u=read(),v=read();
		Add(u,v);Add(v,u);
	}
	init(1,0);
	dfs(1,0);
	for(int i=1;i<=n;i++){
		write(ans[i]);putchar('\n');
	}
	return 0;
}


#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))

namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
	bool IOerror=0;
	inline char nc() {
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend) {
			p1=buf;
			pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1) {
				IOerror=1;
				return -1;
			}
		}
		return *p1++;
	}
	inline bool blank(char ch) {
		return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
	}
	template<class T> inline bool read(T &x) {
		bool sign=0;
		char ch=nc();
		x=0;
		for(; blank(ch); ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	template<class T,class... U>bool read(T& h,U&... t) {
		return read(h)&&read(t...);
	}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int INF = 0x3f3f3f3f;
const int N = 1e6+1;

struct node {
	int ls,rs,ma;
} tree[N * 38];

int ans[N],dep[N];
int root[N],cnt;
vector<int>e[N];

void pp(int x) {
	int ls=tree[x].ls;
	int rs=tree[x].rs;
	tree[x].ma=max(tree[ls].ma,tree[rs].ma);
}

void ins(int &x,int l,int r,int pos) {
	if(!x) x=++cnt;
	if(l==r) {
		tree[x].ma++;
		return ;
	}
	int mid=l+r>>1;
	if(pos<=mid) ins(tree[x].ls,l,mid,pos);
	else ins(tree[x].rs,mid+1,r,pos);
	pp(x);
}

int merge(int x,int y,int l,int r) {
	if( !x || !y) return x?x:y;
	if(l==r) {
		tree[x].ma+=tree[y].ma;
		return x;
	}
	int mid=l+r>>1;
	tree[x].ls=merge(tree[x].ls,tree[y].ls,l,mid);
	tree[x].rs=merge(tree[x].rs,tree[y].rs,mid+1,r);
	pp(x);
	return x;
}

int query(int x,int l,int r){
	if(l==r) return l;
	int mid=l+r>>1;
	int ls=tree[x].ls;
	int rs=tree[x].rs;
	if(tree[ls].ma>=tree[rs].ma) return query(ls,l,mid);
	else return query(rs,mid+1,r);
}

void dfs(int u,int f) {
	dep[u]=dep[f]+1;
	ins(root[u],1,N,dep[u]);
	for(auto v:e[u]) {
		if(v==f) continue;
		dfs(v,u);
		root[u]=merge(root[u],root[v],1,N);
	}
	ans[u]=query(root[u],1,N)-dep[u];
}

int main() {

#ifdef xiaofan
	freopen("1.in","r",stdin);
	freopen("1.out","w",stdout);
#endif

	int n;
	cin>>n;
	for(int i=1; i<n; i++) {
		int u,v;
		cin>>u>>v;
		e[u].pb(v);
		e[v].pb(u);
	}
	dfs(1,0);
	for(int i=1; i<=n; i++) cout<<ans[i]<<endl;

	return 0;
}


#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))

namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
	bool IOerror=0;
	inline char nc() {
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend) {
			p1=buf;
			pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1) {
				IOerror=1;
				return -1;
			}
		}
		return *p1++;
	}
	inline bool blank(char ch) {
		return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
	}
	template<class T> inline bool read(T &x) {
		bool sign=0;
		char ch=nc();
		x=0;
		for(; blank(ch); ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	template<class T,class... U>bool read(T& h,U&... t) {
		return read(h)&&read(t...);
	}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int INF = 0x3f3f3f3f;
const int N = 1e6+1;

struct node {
	int ls,rs,ma,id;
} tree[N * 31];

int ans[N],dep[N];
int root[N],cnt;
vector<int>e[N];

void pp(int x) {
	int ls=tree[x].ls;
	int rs=tree[x].rs;
	if(tree[ls].ma>=tree[rs].ma) {
		tree[x].id=tree[ls].id;
		tree[x].ma=tree[ls].ma;
		return ;
	} else {
		tree[x].id=tree[rs].id;
		tree[x].ma=tree[rs].ma;
		return ;
	}
}

void ins(int &x,int l,int r,int pos) {
	if(!x) x=++cnt;
	if(l==r) {
		tree[x].ma++;
		tree[x].id=l;
		return ;
	}
	int mid=l+r>>1;
	if(pos<=mid) ins(tree[x].ls,l,mid,pos);
	else ins(tree[x].rs,mid+1,r,pos);
	pp(x);
}

int merge(int x,int y,int l,int r) {
	if( !x || !y) return x?x:y;
	if(l==r) {
		tree[x].ma+=tree[y].ma;
		tree[x].id=l;
		return x;
	}
	int mid=l+r>>1;
	tree[x].ls=merge(tree[x].ls,tree[y].ls,l,mid);
	tree[x].rs=merge(tree[x].rs,tree[y].rs,mid+1,r);
	pp(x);
	return x;
}

void dfs(int u,int f) {
	dep[u]=dep[f]+1;
	ins(root[u],1,N,dep[u]);
	for(auto v:e[u]) {
		if(v==f) continue;
		dfs(v,u);
		root[u]=merge(root[u],root[v],1,N);
	}
	ans[u]=tree[root[u]].id-dep[u];
}

int main() {

#ifdef xiaofan
	freopen("1.in","r",stdin);
	freopen("1.out","w",stdout);
#endif

	int n;
	cin>>n;
	for(int i=1; i<n; i++) {
		int u,v;
		cin>>u>>v;
		e[u].pb(v);
		e[v].pb(u);
	}
	dfs(1,0);
	for(int i=1; i<=n; i++) cout<<ans[i]<<endl;

	return 0;
}


#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))

namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
	bool IOerror=0;
	inline char nc() {
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend) {
			p1=buf;
			pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1) {
				IOerror=1;
				return -1;
			}
		}
		return *p1++;
	}
	inline bool blank(char ch) {
		return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
	}
	template<class T> inline bool read(T &x) {
		bool sign=0;
		char ch=nc();
		x=0;
		for(; blank(ch); ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	template<class T,class... U>bool read(T& h,U&... t) {
		return read(h)&&read(t...);
	}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int INF = 0x3f3f3f3f;
const int N = 1e6+10;

struct node {
	int ls,rs,ma,id;
} tree[N * 40];

int ans[N],dep[N];
int root[N],cnt;
vector<int>e[N];

void pp(int x) {
	int ls=tree[x].ls;
	int rs=tree[x].rs;
	if(tree[ls].ma>=tree[rs].ma) {
		tree[x].id=tree[ls].id;
		tree[x].ma=tree[ls].ma;
		return ;
	} else {
		tree[x].id=tree[rs].id;
		tree[x].ma=tree[rs].ma;
		return ;
	}
}

void ins(int &x,int l,int r,int pos) {
	if(!x) x=++cnt;
	if(l==r) {
		tree[x].ma++;
		tree[x].id=l;
		return ;
	}
	int mid=l+r>>1;
	if(pos<=mid) ins(tree[x].ls,l,mid,pos);
	else ins(tree[x].rs,mid+1,r,pos);
	pp(x);
}

int merge(int x,int y,int l,int r) {
	if( !x || !y) return x?x:y;
	if(l==r) {
		tree[x].ma+=tree[y].ma;
		tree[x].id=l;
		return x;
	}
	int mid=l+r>>1;
	tree[x].ls=merge(tree[x].ls,tree[y].ls,l,mid);
	tree[x].rs=merge(tree[x].rs,tree[y].rs,mid+1,r);
	pp(x);
	return x;
}

void dfs(int u,int f) {
	dep[u]=dep[f]+1;
	ins(root[u],1,N,dep[u]);
	for(auto v:e[u]) {
		if(v==f) continue;
		dfs(v,u);
		root[u]=merge(root[u],root[v],1,N);
	}
	ans[u]=tree[root[u]].id-dep[u];
}

int main() {

#ifdef xiaofan
	freopen("1.in","r",stdin);
	freopen("1.out","w",stdout);
#endif

	int n;
	cin>>n;
	for(int i=1; i<n; i++) {
		int u,v;
		cin>>u>>v;
		e[u].pb(v);
		e[v].pb(u);
	}
	dfs(1,0);
	for(int i=1; i<=n; i++) cout<<ans[i]<<endl;

	return 0;
}


    #include <algorithm>
    #include <bitset>
    #include <deque>
    #include <cmath>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <iostream>
    #include <list>
    #include <map>
    #include <queue>
    #include <set>
    #include <sstream>
    #include <stack>
    #include <string>
    #include <utility>
    #include <vector>
    #include <functional>
    #include <numeric>
    #include <iomanip>
    #include <ctime>

    #define fst first
    #define snd second
    #define all(x) (x).begin(), (x).end()
    #define clr(a, v) memset(a, v, sizeof(a))
    #define pb push_back
    #define mp make_pair
    #define sz(x) (int)(x.size())
    #define FORN(i,s,n) for(int i=s;i<(int)(n);i++)
    #define FOR(i,n) FORN(i,0,n)
    #define FORIT(i,x) for( typeof x.begin()  i=x.begin(); i!=x.end(); i++ )
    #define trace(x)    cerr << #x << ": " << x << endl;
    #define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl;

    using namespace std;

    typedef long long int64;
    typedef vector <int> vi;
    typedef pair <int,int> ii;
    typedef vector <string> vs;
    typedef vector <ii> vii;

    const int INF = 1e9+9;

    vii in[1010];
    vii out[1010];
    vi vis(1010,0);

    ii fdfs(int v) {
        vis[v]=1;
        if ( !sz(out[v]) )    return mp( v ,INF );
        if ( vis[out[v][0].fst] ) return mp( -1,INF );
        ii aux=fdfs(out[v][0].fst);
        aux.snd = min( aux.snd , out[v][0].snd );
        return aux;
    }

    int main(){
        int N,M,v,w,c;
        cin>>N>>M;
        FOR(i,M){
            cin>> v >> w >> c ;
            v--;w--;
            out[v].pb ( mp ( w , c ) );
             in[w].pb ( mp ( v , c ) );
        }
        vector < pair <int, ii> > ans;

        FOR(i,N){
            if (!sz(in[i])) {
                ii aux=fdfs(i);
                //trace2(aux.fst,aux.snd);
                if(aux.fst!=-1) ans.pb ( mp ( i , aux ) );
            }
        }
        sort(all(ans));
        cout<<sz(ans)<<endl;
        FOR(i,sz(ans)) cout<<ans[i].fst+1<<" "<<ans[i].snd.fst+1<<" "<<ans[i].snd.snd<<endl;
    }


#include <bits/stdc++.h>
#define pb push_back
#define sz(x) x.size()
#define F first
#define S second
#define mp make_pair
#define ll long long
#define sqr(x) ((x)*(x))
#define inf 1e18
using namespace std;
    ll a[1000010], b[1000], d[100010][26], p[10010];
    ll mn=inf, mx=-inf, ans, cnt, sm=1, n, m;
    bool ok, okk, u[1000010], uu[310][310], uk[1000010];
    char ck[510][510], ch[100010];
    int dx[4]={0, 1, 0, -1}, dy[4]={-1, 0, 1, 0};
    vector <int> g[900010];
    ll ls=-1;
    vector <pair <ll, ll> > v[1110];

void dfs(ll a){
	u[a]=true;
	for(int i=0;i<sz(v[a]);i++){
		ll to=v[a][i].F;
		mn=min(mn, v[a][i].S);
		ls=v[a][i].F;
		dfs(to);
	}
}

int main(){

    //freopen ("input.txt","r",stdin); freopen ("output.txt","w",stdout);

    vector <pair <ll, pair <ll, ll> > > vv;
    cin>>n>>m;
    for(int i=0;i<m;i++){
    	ll x, y, dd;
    	cin>>x>>y>>dd;
    	v[x].pb(mp(y, dd));
    	u[y]=true;
    }
    for(int i=1;i<=n;i++){
    	if(!u[i]){
    	    ls=-1;
    	    mn=inf;
    		dfs(i);
    		if(ls!=-1){
    			vv.pb(mp(i, mp(ls, mn)));
    		}
    	}
    }
    cout<<sz(vv)<<endl;
    for(int i=0;i<sz(vv);i++){
    	cout<<vv[i].F<<' '<<vv[i].S.F<<' '<<vv[i].S.S<<endl;
    }

    return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define sz(x) x.size()
#define F first
#define S second
#define mp make_pair
#define ll long long
#define sqr(x) ((x)*(x))
#define inf 1e18
using namespace std;
    ll a[1000010], b[1000], d[100010][26], p[10010];
    ll mn=inf, mx=-inf, ans, cnt, sm=1, n, m;
    bool ok, okk, u[1000010], uu[310][310], uk[1000010];
    char ck[510][510], ch[100010];
    int dx[4]={0, 1, 0, -1}, dy[4]={-1, 0, 1, 0};
    vector <int> g[900010];
    ll ls=-1;
    vector <pair <ll, ll> > v[1110];

void dfs(ll a){
	u[a]=true;
	for(int i=0;i<sz(v[a]);i++){
		ll to=v[a][i].F;
		mn=min(mn, v[a][i].S);
		ls=v[a][i].F;
		dfs(to);
	}
}

int main(){

    //freopen ("input.txt","r",stdin); freopen ("output.txt","w",stdout);

    vector <pair <ll, pair <ll, ll> > > vv;
    cin>>n>>m;
    for(int i=0;i<m;i++){
    	ll x, y, dd;
    	cin>>x>>y>>dd;
    	v[x].pb(mp(y, dd));
    	u[y]=true;
    }
    for(int i=1;i<=n;i++){
    	if(!u[i]){
    	    ls=-1;
    	    mn=inf;
    		dfs(i);
    		if(ls!=-1){
    		vv.pb(mp(i, mp(ls, mn)));}
    	}
    }
    cout<<sz(vv)<<endl;
    for(int i=0;i<sz(vv);i++){
    	cout<<vv[i].F<<' '<<vv[i].S.F<<' '<<vv[i].S.S<<endl;
    }

    return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define sz(x) x.size()
#define F first
#define S second
#define mp make_pair
#define ll long long
#define sqr(x) ((x)*(x))
#define inf 1e18
using namespace std;
    ll a[1000010], b[1000], d[100010][26], p[10010];
    ll mn=inf, mx=-inf, ans, cnt, sm=1, n, m;
    bool ok, okk, u[1000010], uu[310][310], uk[1000010];
    char ck[510][510], ch[100010];
    int dx[4]={0, 1, 0, -1}, dy[4]={-1, 0, 1, 0};
    vector <int> g[900010];
    ll ls=-1;
    vector <pair <ll, ll> > v[1110];

void dfs(ll a, ll b){
	u[a]=true;
	for(int i=0;i<sz(v[a]);i++){
		ll to=v[a][i].F;
		//cout<<a<<' '<<v[a][i].F<<' '<<v[a][i].S<<endl;
		mn=min(mn, v[a][i].S);
		ls=v[a][i].F;
		dfs(to, ls);
	}
}

int main(){

    //freopen ("input.txt","r",stdin); freopen ("output.txt","w",stdout);

    vector <pair <ll, pair <ll, ll> > > vv;
    cin>>n>>m;
    for(int i=0;i<m;i++){
    	ll x, y, dd;
    	cin>>x>>y>>dd;
    	v[x].pb(mp(y, dd));
    	u[y]=true;
    }
    for(int i=1;i<=n;i++){
    	if(!u[i]){
    	    ls=-1;
    	    mn=inf;
    		dfs(i, ls);
    		if(ls!=-1){
    		vv.pb(mp(i, mp(ls, mn)));}
    	}
    }
    //cout<<endl;
    cout<<sz(vv)<<endl;
    for(int i=0;i<sz(vv);i++){
    	cout<<vv[i].F<<' '<<vv[i].S.F<<' '<<vv[i].S.S<<endl;
    }

    return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define sz(x) x.size()
#define F first
#define S second
#define mp make_pair
#define ll long long
#define sqr(x) ((x)*(x))
#define inf 1e18
using namespace std;
    ll a[1000010], b[1000], d[100010][26], p[10010];
    ll mn=inf, mx=-inf, ans, cnt, sm=1, n, m;
    bool ok, okk, u[1000010], uu[310][310], uk[1000010];
    char ck[510][510], ch[100010];
    int dx[4]={0, 1, 0, -1}, dy[4]={-1, 0, 1, 0};
    vector <int> g[900010];
    ll ls=-1;
    vector <pair <ll, ll> > v[1110];

void dfs(ll a, ll b){
	u[a]=true;
	for(int i=0;i<sz(v[a]);i++){
		ll to=v[a][i].F;
		//cout<<a<<' '<<v[a][i].F<<' '<<v[a][i].S<<endl;
		mn=min(mn, v[a][i].S);
		ls=v[a][i].F;
		dfs(to, ls);
	}
}

int main(){

    //freopen ("input.txt","r",stdin); freopen ("output.txt","w",stdout);

    vector <pair <ll, pair <ll, ll> > > vv;
    cin>>n>>m;
    for(int i=0;i<m;i++){
    	ll x, y, dd;
    	cin>>x>>y>>dd;
    	v[x].pb(mp(y, dd));
    	u[y]=true;
    }
    for(int i=1;i<=n;i++){
    	if(!u[i]){
    	    ls=-1;
    	    mn=inf;
    		dfs(i, ls);
    		vv.pb(mp(i, mp(ls, mn)));
    	}
    }
    //cout<<endl;
    cout<<sz(vv)<<endl;
    for(int i=0;i<sz(vv);i++){
    	cout<<vv[i].F<<' '<<vv[i].S.F<<' '<<vv[i].S.S<<endl;
    }

    return 0;
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#include <numeric>
#include <sstream>
#include <iostream>
#include <iomanip>
#include<cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>

using namespace std;

typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef double ld;
typedef vector<ld> vld;

#define forn(i, n) for(int i = 0; i < (int)(n); i++)
#define fore(i, a, n) for(int i = (int)(a); i < (int)(n); i++)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; i--)
#define pb push_back
#define mp make_pair
#define fs first
#define sc second
#define last(a) int(a.size() - 1)
#define all(a) a.begin(), a.end()
#define fornl(i,n)   for(ll i=0;i<n;i++)
#define len			  size()
#define s(n)          scanf("%d",&n);
#define slld(n)       scanf("%lld",&n);
#define sf(n)         scanf("%lf",&n);
#define ss(n)         scanf("%s",n);
#define MEM(a,b)      memset(a,(b),sizeof(a))  //memset(arr,0,sizeof(arr))
#define MOD           1000000007
#define nl printf("\n");

    const long double EPS = 1E-9;
    const int INF = (int) 1E9;
    const ll INF64 = (ll) 1E18;
	vector<pair<long long,int> > v[1001];

	bool vis[1001]={0};
	struct s {
		int a,b,c;
	};
	vector<s> ans;
	bool dfs(int a,int  b,int d) {
		if(v[a].size()==0) {
			s ob;
			ob.a=b+1; ob.b=a+1;ob.c=d;
			ans.pb(ob);
			return 0;
		}
		vis[a]=1;
		forn(i,v[a].size()) {
			if(vis[v[a][i].fs]==0 )
				dfs(v[a][i].fs,b,min(d,v[a][i].sc));
		}
		}

    int main() {
		int n,p;
		cin>>n>>p;
		forn(i,p) {
			int x,y,z;
			cin>>x>>y>>z;
			x--,y--;
			v[x].pb(mp(y,z));
		}
		forn(i,n) {
			if(vis[i]==0 && v[i].size()>0 )
			dfs(i,i,v[i][0].sc);
		}
		cout<<ans.size()<<endl;
		forn(i,ans.size()) cout<<ans[i].a<<" "<<ans[i].b<<" "<<ans[i].c<<endl;
    }


#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#include <numeric>
#include <sstream>
#include <iostream>
#include <iomanip>
#include<cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>

using namespace std;

typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef double ld;
typedef vector<ld> vld;

#define forn(i, n) for(int i = 0; i < (int)(n); i++)
#define fore(i, a, n) for(int i = (int)(a); i < (int)(n); i++)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; i--)
#define pb push_back
#define mp make_pair
#define fs first
#define sc second
#define last(a) int(a.size() - 1)
#define all(a) a.begin(), a.end()
#define fornl(i,n)   for(ll i=0;i<n;i++)
#define len			  size()
#define s(n)          scanf("%d",&n);
#define slld(n)       scanf("%lld",&n);
#define sf(n)         scanf("%lf",&n);
#define ss(n)         scanf("%s",n);
#define MEM(a,b)      memset(a,(b),sizeof(a))  //memset(arr,0,sizeof(arr))
#define MOD           1000000007
#define nl printf("\n");

    const long double EPS = 1E-9;
    const int INF = (int) 1E9;
    const ll INF64 = (ll) 1E18;
	vector<pair<long long,int> > v[1001];

	bool vis[1001]={0};
	struct s {
		int a,b,c;
	};
	vector<s> ans;
	bool dfs(int a,int  b,int d) {
		if(v[a].size()==0) {
			s ob;
			ob.a=b+1; ob.b=a+1;ob.c=d;
			ans.pb(ob);
			return 0;
		}
		vis[a]=1;
		forn(i,v[a].size()) {
			if(vis[v[a][i].fs]==0 )
				dfs(v[a][i].fs,b,min(d,v[a][i].sc));
		}
		}

    int main() {
		int n,p;
		cin>>n>>p;
		map<int,int> m;
		forn(i,p) {
			int x,y,z;
			cin>>x>>y>>z;
			x--,y--;
			m[x]++,m[y]++;
			v[x].pb(mp(y,z));
		}
		forn(i,n) {
			if(vis[i]==0 && v[i].size()==1 &&m[i]==1) {
				cout<<i<<endl;
			dfs(i,i,v[i][0].sc);
			}
		}
		sort(all(ans));
		cout<<ans.size()<<endl;
		forn(i,ans.size()) cout<<ans[i].a<<" "<<ans[i].b<<" "<<ans[i].c<<endl;
    }


#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#include <numeric>
#include <sstream>
#include <iostream>
#include <iomanip>
#include<cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>

using namespace std;

typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef double ld;
typedef vector<ld> vld;

#define forn(i, n) for(int i = 0; i < (int)(n); i++)
#define fore(i, a, n) for(int i = (int)(a); i < (int)(n); i++)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; i--)
#define pb push_back
#define mp make_pair
#define fs first
#define sc second
#define last(a) int(a.size() - 1)
#define all(a) a.begin(), a.end()
#define fornl(i,n)   for(ll i=0;i<n;i++)
#define len			  size()
#define s(n)          scanf("%d",&n);
#define slld(n)       scanf("%lld",&n);
#define sf(n)         scanf("%lf",&n);
#define ss(n)         scanf("%s",n);
#define MEM(a,b)      memset(a,(b),sizeof(a))  //memset(arr,0,sizeof(arr))
#define MOD           1000000007
#define nl printf("\n");

    const long double EPS = 1E-9;
    const int INF = (int) 1E9;
    const ll INF64 = (ll) 1E18;
	vector<pair<long long,int> > v[1001];

	bool vis[1001]={0};
	struct s {
		int a,b,c;
	};
	vector<s> ans;
	bool dfs(int a,int  b,int d) {
		if(v[a].size()==0) {
			s ob;
			ob.a=b+1; ob.b=a+1;ob.c=d;
			ans.pb(ob);
			return 0;
		}
		vis[a]=1;
		forn(i,v[a].size()) {
			if(vis[v[a][i].fs]==0 )
				dfs(v[a][i].fs,b,min(d,v[a][i].sc));
		}
		}
	bool operator < (s ob1,s ob2) {
		if(ob1.a<ob2.a) return 1;
		return 0;
	}
    int main() {
		int n,p;
		cin>>n>>p;
		map<int,int> m;
		forn(i,p) {
			int x,y,z;
			cin>>x>>y>>z;
			x--,y--;
			m[x]++,m[y]++;
			v[x].pb(mp(y,z));
		}
		forn(i,n) {
			if(vis[i]==0 && v[i].size()==1 &&m[i]==1) {
				//cout<<i<<endl;
			dfs(i,i,v[i][0].sc);
			}
		}
		sort(all(ans));
		cout<<ans.size()<<endl;
		forn(i,ans.size()) cout<<ans[i].a<<" "<<ans[i].b<<" "<<ans[i].c<<endl;
    }


#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int INF = 1<<30;
int head[1010];
bool IsIn[1010];
int n, m;
struct EDGE{
    int u, v, c, next;
};
EDGE edg[1010], prit[1010];
int e, cnt;
void AddEdge(int u, int v, int c)
{
    edg[e].u = u;
    edg[e].v = v;
    edg[e].c = c;
    edg[e].next = head[u];
    head[u] = e;
}
void dfs(int i, int maxd)
{
    if(head[i] == -1){
        prit[cnt].v = i;
        prit[cnt++].c = maxd;
        return ;
    }
    for(int ne = head[i]; ne != -1; ne = edg[ne].next){
        dfs(edg[ne].v, min(maxd, edg[ne].c));
        break;
    }
}

int main()
{
    //freopen("input.txt", "r", stdin);
    int d, u, v;
    memset(head, -1, sizeof(head));
    memset(IsIn, 0, sizeof(IsIn));
    scanf("%d %d", &n, &m);
    for(e = 0; e < m; e++){
        scanf("%d %d %d", &u, &v, &d);
        AddEdge(u, v, d);
        IsIn[v] = true;
    }
    cnt = 0;
    for(int i = 1; i <= n; i++){
        if(!IsIn[i]){
            //printf("%d\n", i);
            prit[cnt].u = i;
            dfs(i, INF);
            if(prit[cnt - 1].v == i)
                cnt--;
        }
    }
    printf("%d\n", cnt);
    for(int i = 0; i < cnt; i++){
        printf("%d %d %d\n", prit[i].u, prit[i].v, prit[i].c);
    }
    return 0;
}


#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int INF = 1<<30;
int head[1010];
bool IsIn[1010];
int n, m;
struct EDGE{
    int u, v, c, next;
};
EDGE edg[1010], prit[1010];
int e, cnt;
void AddEdge(int u, int v, int c)
{
    edg[e].u = u;
    edg[e].v = v;
    edg[e].c = c;
    edg[e].next = head[u];
    head[u] = e;
}
void dfs(int i, int maxd)
{
    if(head[i] == -1){
        prit[cnt].v = i;
        prit[cnt++].c = maxd;
        return ;
    }
    for(int ne = head[i]; ne != -1; ne = edg[ne].next){
        dfs(edg[ne].v, min(maxd, edg[ne].c));
        break;
    }
}

int main()
{
    //freopen("input.txt", "r", stdin);
    int d, u, v;
    memset(head, -1, sizeof(head));
    memset(IsIn, 0, sizeof(IsIn));
    scanf("%d %d", &n, &m);
    for(e = 0; e < m; e++){
        scanf("%d %d %d", &u, &v, &d);
        AddEdge(u, v, d);
        IsIn[v] = true;
    }
    cnt = 0;
    for(int i = 1; i <= n; i++){
        if(!IsIn[i]){
            //printf("%d\n", i);
            prit[cnt].u = i;
            dfs(i, INF);
        }
    }
    printf("%d\n", cnt);
    for(int i = 0; i < cnt; i++){
        printf("%d %d %d\n", prit[i].u, prit[i].v, prit[i].c);
    }
    return 0;
}


#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int INF = 1<<30;
int head[1010];
bool IsIn[1010];
int n, m;
struct EDGE{
    int u, v, c, next;
};
EDGE edg[1010], prit[1010];
int e, cnt;
void AddEdge(int u, int v, int c)
{
    edg[e].u = u;
    edg[e].v = v;
    edg[e].c = c;
    edg[e].next = head[u];
    head[u] = e;
}
void dfs(int i, int maxd)
{
    if(head[i] == -1){
        prit[cnt].v = i;
        prit[cnt++].c = maxd;
        return ;
    }
    for(int ne = head[i]; ne != -1; ne = edg[ne].next){
        dfs(edg[ne].v, min(maxd, edg[ne].c));
        break;
    }
}

int main()
{
    //freopen("input.txt", "r", stdin);
    int d, u, v;
    memset(head, -1, sizeof(head));
    memset(IsIn, 0, sizeof(IsIn));
    scanf("%d %d", &n, &m);
    for(e = 0; e < m; e++){
        scanf("%d %d %d", &u, &v, &d);
        AddEdge(u, v, d);
        IsIn[v] = true;
    }
    cnt = 0;
    for(int i = 1; i <= n; i++){
        if(!IsIn[i]){
            //printf("%d\n", i);
            prit[cnt].u = i;
            dfs(i, INF);
            if(prit[cnt].v == i)
                cnt--;
        }
    }
    printf("%d\n", cnt);
    for(int i = 0; i < cnt; i++){
        printf("%d %d %d\n", prit[i].u, prit[i].v, prit[i].c);
    }
    return 0;
}


#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <cstring>
#include <cstdio>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;

#define REP(i,b,n) for(int i=b;i<(int)n;i++)
#define rep(i,n) REP(i,0,n)
#define foreach(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();i++)

struct Result {
  int tank, tap, diameter;
  Result():tank(0),tap(0),diameter(0){}
  bool operator<(const Result& a) const {
    return tank < a.tank;
  }
};

int n, p, es[1002][1002], a, b, res_size;
bool used[1002];
Result result[1002];

void dfs(int from, int cur, int meter) {
  if (used[cur]) return;
  used[cur] = true;
  rep(i,n) if (es[cur][i] > 0) {
    dfs(from, i, min(meter, es[cur][i])); return;
  }
  if (from != cur) {
    result[res_size].tank = from+1;
    result[res_size].tap = cur+1;
    result[res_size].diameter = meter;
    res_size++;
  }
}

int main(int argc, char* argv[]) {
  memset(es, -1, sizeof es);
  set<int> taps;
  cin>>n>>p;
  rep(i,p) {
    cin>>a>>b;
    a--; b--;
    taps.insert(b);
    cin>>es[a][b];
  }
  fill(used, used + n, false);
  rep(i,n) {
    if (!used[i] && !taps.count(i)) dfs(i, i, 1<<28);
  }

  if (res_size) {
    sort(result, result+res_size);
    printf("%d\n", res_size);
    rep(i,res_size)
      printf("%d %d %d\n", result[i].tank, result[i].tap, result[i].diameter);
  } else {
    puts("0");
  }
  return 0;
}


#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

#define REP(i,b,n) for(int i=b;i<(int)n;i++)
#define rep(i,n) REP(i,0,n)
#define foreach(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();i++)

struct Result {
  int tank, tap, diameter;
  Result():tank(0),tap(0),diameter(0){}
  bool operator<(const Result& a) const {
    return tank < a.tank;
  }
};

int n, p, es[1002][1002], a, b, res_size;
bool used[1002];
Result result[1002];

void dfs(int from, int cur, int meter) {
  if (used[cur]) return;
  used[cur] = true;
  bool check = true;
  rep(i,n) if (es[cur][i] > 0) {
    check = false;
    if (es[cur][i] >= meter) {
      if (meter == 0) dfs(from, i, es[cur][i]);
      else dfs(from, i, meter);
      return;
    }
  }
  if (from != cur && check) {
    result[res_size].tank = from+1;
    result[res_size].tap = cur+1;
    result[res_size].diameter = meter;
    res_size++;
  }
}

int main(int argc, char* argv[]) {
  memset(es, -1, sizeof es);
  cin>>n>>p;
  rep(i,p) {
    cin>>a>>b;
    a--; b--;
    cin>>es[a][b];
  }
  fill(used, used + n, false);
  rep(i,n) {
    if (!used[i]) dfs(i, i, 0);
  }

  if (res_size) {
    sort(result, result+res_size);
    rep(i,res_size)
      printf("%d %d %d\n", result[i].tank, result[i].tap, result[i].diameter);
  } else {
    puts("0");
  }
  return 0;
}


#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

#define REP(i,b,n) for(int i=b;i<(int)n;i++)
#define rep(i,n) REP(i,0,n)
#define foreach(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();i++)

struct Result {
  int tank, tap, diameter;
  Result():tank(0),tap(0),diameter(0){}
  bool operator<(const Result& a) const {
    return tank < a.tank;
  }
};

int n, p, es[1002][1002], a, b, res_size;
bool used[1002];
Result result[1002];

void dfs(int from, int cur, int meter) {
  if (used[cur]) return;
  used[cur] = true;
  int max_pipe = 0, loc = -1;
  bool check = true;
  rep(i,n) if (es[cur][i] > 0) {
    check = false;
    if (es[cur][i] >= meter && es[cur][i] > max_pipe) {
      max_pipe = es[cur][i];
      loc = i;
    }
  }
  if (loc != -1) {
    if (meter == 0) dfs(from, loc, max_pipe);
    else dfs(from, loc, meter);
    return;
  }
  if (from != cur && check) {
    result[res_size].tank = from+1;
    result[res_size].tap = cur+1;
    result[res_size].diameter = meter;
    res_size++;
  }
}

int main(int argc, char* argv[]) {
  memset(es, -1, sizeof es);
  cin>>n>>p;
  rep(i,p) {
    cin>>a>>b;
    a--; b--;
    cin>>es[a][b];
  }
  fill(used, used + n, false);
  rep(i,n) {
    if (!used[i]) dfs(i, i, 0);
  }

  if (res_size) {
    sort(result, result+res_size);
    printf("%d\n", res_size);
    rep(i,res_size)
      printf("%d %d %d\n", result[i].tank, result[i].tap, result[i].diameter);
  } else {
    puts("0");
  }
  return 0;
}


#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

#define REP(i,b,n) for(int i=b;i<(int)n;i++)
#define rep(i,n) REP(i,0,n)
#define foreach(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();i++)

struct Result {
  int tank, tap, diameter;
  Result():tank(0),tap(0),diameter(0){}
  bool operator<(const Result& a) const {
    return tank < a.tank;
  }
};

int n, p, es[1002][1002], a, b, res_size;
bool used[1002];
Result result[1002];

void dfs(int from, int cur, int meter) {
  if (used[cur]) return;
  used[cur] = true;
  rep(i,n) if (es[cur][i] > 0) {
    //dfs(from, i, (meter==0)?es[cur][i]:min(meter, es[cur][i])); return;
    dfs(from, i, min(meter, es[cur][i])); return;
  }
  if (from != cur) {
    result[res_size].tank = from+1;
    result[res_size].tap = cur+1;
    result[res_size].diameter = meter;
    res_size++;
  }
}

int main(int argc, char* argv[]) {
  memset(es, -1, sizeof es);
  cin>>n>>p;
  rep(i,p) {
    cin>>a>>b;
    a--; b--;
    cin>>es[a][b];
  }
  fill(used, used + n, false);
  rep(i,n) {
    if (!used[i]) dfs(i, i, 1<<28);
  }

  if (res_size) {
    sort(result, result+res_size);
    printf("%d\n", res_size);
    rep(i,res_size)
      printf("%d %d %d\n", result[i].tank, result[i].tap, result[i].diameter);
  } else {
    puts("0");
  }
  return 0;
}


#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <cstring>
#include <cstdio>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;

#define REP(i,b,n) for(int i=b;i<(int)n;i++)
#define rep(i,n) REP(i,0,n)
#define foreach(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();i++)

struct Result {
  int tank, tap, diameter;
  Result():tank(0),tap(0),diameter(0){}
  Result(int a, int b, int c):tank(a),tap(b),diameter(c){}
  bool operator<(const Result& a) const {return tank < a.tank;}
};

int n, p, es[1002][1002], a, b, res_size;
bool used[1002];
Result result[1002];

void dfs(int from, int cur, int meter) {
  if (used[cur]) return;
  used[cur] = true;
  rep(i,n) if (es[cur][i] > 0) {
    dfs(from, i, min(meter, es[cur][i])); return;
  }
  if (from != cur) {
    /*
    result[res_size].tank = from+1;
    result[res_size].tap = cur+1;
    result[res_size].diameter = meter;
    */
    result[res_size] = Result(from+1, cur+1, meter);
    res_size++;
  }
}

int main(int argc, char* argv[]) {
  memset(es, -1, sizeof es);
  set<int> taps;
  cin>>n>>p;
  rep(i,p) {
    cin>>a>>b;
    a--; b--;
    taps.insert(b);
    cin>>es[a][b];
  }
  fill(used, used + n, false);
  rep(i,n) {
    if (!used[i] && !taps.count(i)) dfs(i, i, 1<<28);
  }

  if (res_size) {
    sort(result, result+res_size);
    printf("%d\n", res_size);
    rep(i,res_size)
      printf("%d %d %d\n", result[i].tank, result[i].tap, result[i].diameter);
  } else {
    puts("0");
  }
  return 0;
}


#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

#define REP(i,b,n) for(int i=b;i<(int)n;i++)
#define rep(i,n) REP(i,0,n)
#define foreach(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();i++)

struct Result {
  int tank, tap, diameter;
  Result():tank(0),tap(0),diameter(0){}
  bool operator<(const Result& a) const {
    return tank < a.tank;
  }
};

int n, p, es[1002][1002], a, b, res_size;
bool used[1002];
Result result[1002];

void dfs(int from, int cur, int meter) {
  if (used[cur]) return;
  used[cur] = true;
  bool check = true;
  rep(i,n) if (es[cur][i] > 0) {
    check = false;
    if (es[cur][i] >= meter) {
      if (meter == 0) dfs(from, i, es[cur][i]);
      else dfs(from, i, meter);
      return;
    }
  }
  if (from != cur && check) {
    result[res_size].tank = from+1;
    result[res_size].tap = cur+1;
    result[res_size].diameter = meter;
    res_size++;
  }
}

int main(int argc, char* argv[]) {
  memset(es, -1, sizeof es);
  cin>>n>>p;
  rep(i,p) {
    cin>>a>>b;
    a--; b--;
    cin>>es[a][b];
  }
  fill(used, used + n, false);
  rep(i,n) {
    if (!used[i]) dfs(i, i, 0);
  }

  if (res_size) {
    sort(result, result+res_size);
    printf("%d\n", res_size);
    rep(i,res_size)
      printf("%d %d %d\n", result[i].tank, result[i].tap, result[i].diameter);
  } else {
    puts("0");
  }
  return 0;
}


/*
 * Author:王禹秋(jywyq)
 * Date:20160312
 */
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
#define LL long long
int to[1010],pre[1010],val[1010];
int ans[1010][3],cnt=0;
int main(){
	int n,m;
	cin>>n>>m;
	int u,v;
	for(int i=0;i<m;i++){
		cin>>u;
		cin>>to[u]>>val[u];
		pre[to[u]]=u;
	}
	if(n==m){
		cout<<"0"<<endl;
		return 0;
	}
	for(int i=1;i<=n;i++){
		if(to[i]&&!pre[i]){
			int tmp=i;
			int mi=0xfffffff;
			while(to[tmp]){
				mi=min(mi,val[tmp]);
				tmp=to[tmp];
				//cout<<mi<<endl;
			}
			ans[cnt][0]=i;
			ans[cnt][1]=tmp;
			ans[cnt][2]=mi;
			cnt++;
		}
	}
	cout<<cnt<<endl;
	for(int i=0;i<cnt;i++){
		printf("%d %d %d\n",ans[i][0],ans[i][1],ans[i][2]);
	}

}


/*
 * Author:王禹秋(jywyq)
 * Date:20160312
 */
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
#define LL long long
int to[1010],val[1010];
bool vis[1010];
int ans[1010][3],cnt=0;
int main(){
	int n,m;
	cin>>n>>m;
	int u,v;
	for(int i=0;i<m;i++){
		cin>>u;
		cin>>to[u]>>val[u];
	}
	if(n==m){
		cout<<"0"<<endl;
		return 0;
	}
	for(int i=1;i<=n;i++){
		if(!vis[i]&&to[i]){
			int mi=0xfffffff;
			int tmp=i;
			bool flag=1;
			while(to[tmp]){
				mi=min(mi,val[tmp]);
				tmp=to[tmp];
				if(vis[tmp])flag=0;
			}
			if(flag){
				ans[cnt][0]=i;
				ans[cnt][1]=tmp;
				ans[cnt][2]=val[i];
				cnt++;
				tmp=i;
				while(to[tmp]){
					vis[tmp]=1;
					tmp=to[tmp];
				}
				vis[tmp]=1;
			}

		}
	}
	cout<<cnt<<endl;
	for(int i=0;i<cnt;i++){
		printf("%d %d %d\n",ans[i][0],ans[i][1],ans[i][2]);
	}

}


/*
 * Author:王禹秋(jywyq)
 * Date:20160312
 */
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
#define LL long long
LL to[1010],pre[1010],val[1010];
LL ans[1010][3],cnt=0;
int main(){
	LL n,m;
	int cas=0;
		cin>>n>>m;
		cnt=0;
		memset(to,0,sizeof to);
		memset(pre,0,sizeof pre);
		memset(val,0,sizeof val);
		memset(ans,0,sizeof ans);
		int u,v;
		for(int i=0;i<m;i++){
			cin>>u;
			cin>>to[u]>>val[u];
			pre[to[u]]=u;
		}
		if(n==m){
			cout<<"0"<<endl;
			return 0;
		}
		for(int i=1;i<=n;i++){
			if(to[i]&&!pre[i]){
				int tmp=i;
				LL mi=0xfffffffffffffff;
				while(to[tmp]){
					mi=min(mi,val[tmp]);
					tmp=to[tmp];
				}
				ans[cnt][0]=i;
				ans[cnt][1]=tmp;
				ans[cnt][2]=mi;
				cnt++;
			}
		}
		cout<<cnt<<endl;
		for(int i=0;i<cnt;i++){
			printf("%lld %lld %lld\n",ans[i][0],ans[i][1],ans[i][2]);
		}
}


/*
 * Author:王禹秋(jywyq)
 * Date:20160312
 */
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
#define LL long long
LL to[1010],pre[1010],val[1010];
LL ans[1010][3],cnt=0;
int main(){
	LL n,m;
	int t=1;
	int cas=0;
	while(t--){
		cin>>n>>m;
		cnt=0;
		memset(to,0,sizeof to);
		memset(pre,0,sizeof pre);
		memset(val,0,sizeof val);
		memset(ans,0,sizeof ans);
		int u,v;
		for(int i=0;i<m;i++){
			cin>>u;
			cin>>to[u]>>val[u];
			pre[to[u]]=u;
		}
		if(n==m){
			//printf("Case %d: %d %d\n",++cas,n,0);
			cout<<"0"<<endl;
			continue;
		}
		for(int i=1;i<=n;i++){
			if(to[i]&&!pre[i]){
				int tmp=i;
				LL mi=0xfffffffffffffff;
				while(to[tmp]){
					mi=min(mi,val[tmp]);
					tmp=to[tmp];
					//cout<<mi<<endl;
				}
				ans[cnt][0]=i;
				ans[cnt][1]=tmp;
				ans[cnt][2]=mi;
				cnt++;
			}
		}
		//printf("Case %d: %d %d\n",++cas,n,cnt);
		cout<<cnt<<endl;
		for(int i=0;i<cnt;i++){
			printf("%d %d %d\n",ans[i][0],ans[i][1],ans[i][2]);
		}
	}

}


/*
 * Author:王禹秋(jywyq)
 * Date:20160312
 */
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
#define LL long long
int to[1010],val[1010];
bool vis[1010];
int ans[1010][3],cnt=0;
int main(){
	int n,m;
	cin>>n>>m;
	int u,v;
	for(int i=0;i<m;i++){
		cin>>u;
		cin>>to[u]>>val[u];
	}
	if(n==m){
		cout<<"0"<<endl;
		return 0;
	}
	for(int i=1;i<=n;i++){
		if(!vis[i]&&to[i]){
			vis[i]=1;
			int mi=0xfffffff;
			int tmp=i;
			while(to[tmp]!=0){
				mi=min(mi,val[tmp]);
				tmp=to[tmp];
				vis[tmp]=1;
			}
			ans[cnt][0]=i;
			ans[cnt][1]=tmp;
			ans[cnt][2]=val[i];
			cnt++;
		}
	}
	cout<<cnt<<endl;
	for(int i=0;i<cnt;i++){
		printf("%d %d %d\n",ans[i][0],ans[i][1],ans[i][2]);
	}

}


/*
 * Author:王禹秋(jywyq)
 * Date:20160312
 */
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
#define LL long long
LL to[1010],pre[1010],val[1010];
LL ans[1010][3],cnt=0;
int main(){
	LL n,m;
	int cas=0;
		cin>>n>>m;
		cnt=0;
		memset(to,0,sizeof to);
		memset(pre,0,sizeof pre);
		memset(val,0,sizeof val);
		memset(ans,0,sizeof ans);
		int u,v;
		for(int i=0;i<m;i++){
			cin>>u;
			cin>>to[u]>>val[u];
			pre[to[u]]=u;
		}
		if(n==m){
			cout<<"0"<<endl;
			return 0;
		}
		for(int i=1;i<=n;i++){
			if(to[i]&&!pre[i]){
				int tmp=i;
				LL mi=0xfffffffffffffff;
				while(to[tmp]){
					mi=min(mi,val[tmp]);
					tmp=to[tmp];
				}
				ans[cnt][0]=i;
				ans[cnt][1]=tmp;
				ans[cnt][2]=mi;
				cnt++;
			}
		}
		cout<<cnt<<endl;
		for(int i=0;i<cnt;i++){
			printf("%d %d %d\n",ans[i][0],ans[i][1],ans[i][2]);
		}
}


/*
 * Author:王禹秋(jywyq)
 * Date:20160312
 */
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
#define LL long long
LL to[1010],pre[1010],val[1010];
LL ans[1010][3],cnt=0;
int main(){
	LL n,m;
	int cas=0;
		cin>>n>>m;
		cnt=0;
		memset(to,0,sizeof to);
		memset(pre,0,sizeof pre);
		memset(val,0,sizeof val);
		memset(ans,0,sizeof ans);
		int u,v;
		for(int i=0;i<m;i++){
			cin>>u;
			cin>>to[u]>>val[u];
			pre[to[u]]=u;
		}
		if(n==m){
			cout<<"0"<<endl;
			continue;
		}
		for(int i=1;i<=n;i++){
			if(to[i]&&!pre[i]){
				int tmp=i;
				LL mi=0xfffffffffffffff;
				while(to[tmp]){
					mi=min(mi,val[tmp]);
					tmp=to[tmp];
				}
				ans[cnt][0]=i;
				ans[cnt][1]=tmp;
				ans[cnt][2]=mi;
				cnt++;
			}
		}
		cout<<cnt<<endl;
		for(int i=0;i<cnt;i++){
			printf("%d %d %d\n",ans[i][0],ans[i][1],ans[i][2]);
		}
}


#pragma comment(linker, "/STACK:60000000")

#include <iostream>
#include <stdio.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <algorithm>
#include <cstdlib>
#include <memory.h>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <time.h>
#include <string.h>
#include <cmath>
#include <iomanip>
#include <string>
#include <sstream>

#define mems(a,x) memset(a,x,sizeof a)
using namespace std;
//type definitions
struct corpus
{
    int in,ind,out,outd;
    bool tank,tap;
    corpus()
    {in=0;out=0;}
};
struct rez
{
    int fl,s,f;
};
//var definitions
int n,p,a,b,d;
vector<corpus> g;
vector<rez> ans;
//Function definitions
bool cmp(const rez &a,const rez &b)
{return a.fl>b.fl;}

int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    cin>>n>>p;
    g.resize(n+1);
    for (int i=1;i<=p;i++)
    {
        cin>>a>>b>>d;
        g[a].out=b;
        g[a].outd=d;
        g[b].in=a;
        g[b].ind=d;
    }
    for (int i=1;i<=n;i++)
    {
        if (g[i].in==0)
        {
            if (g[i].out!=0)
            {
            int v=i;
            int push=g[i].outd;
            do
            {
                push=min(push,g[v].outd);
                v=g[v].out;
            }
            while(g[v].out!=0);
            rez r;
            r.fl=push;
            r.s=i;
            r.f=v;
            ans.push_back(r);
            }
        }
    }
    sort(ans.begin(),ans.end(),cmp);
    cout<<ans.size()<<endl;
    for (int i=0;i<ans.size();i++)
    {
        cout<<ans[i].s<<" "<<ans[i].f<<" "<<ans[i].fl<<endl;
    }
    return 0;
}


#pragma comment(linker, "/STACK:60000000")

#include <iostream>
#include <stdio.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <algorithm>
#include <cstdlib>
#include <memory.h>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <time.h>
#include <string.h>
#include <cmath>
#include <iomanip>
#include <string>
#include <sstream>

#define mems(a,x) memset(a,x,sizeof a)
using namespace std;
//type definitions
struct corpus
{
    int in,ind,out,outd;
    bool tank,tap;
    corpus()
    {in=0;out=0;}
};
struct rez
{
    int fl,s,f;
};
//var definitions
int n,p,a,b,d;
vector<corpus> g;
vector<rez> ans;
//Function definitions
bool cmp(const rez &a,const rez &b)
{return a.fl>b.fl;}

int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    cin>>n>>p;
    g.resize(n+1);
    for (int i=1;i<=p;i++)
    {
        cin>>a>>b>>d;
        g[a].out=b;
        g[a].outd=d;
        g[b].in=a;
        g[b].ind=d;
    }
    for (int i=1;i<=n;i++)
    {
        if (g[i].in==0)
        {
            int v=i;
            int push=g[i].outd;
            do
            {
                push=min(push,g[v].outd);
                v=g[v].out;
            }
            while(g[v].out!=0);
            rez r;
            r.fl=push;
            r.s=i;
            r.f=v;
            ans.push_back(r);
        }
    }
    sort(ans.begin(),ans.end(),cmp);
    cout<<ans.size()<<endl;
    for (int i=0;i<ans.size();i++)
    {
        cout<<ans[i].s<<" "<<ans[i].f<<" "<<ans[i].fl<<endl;
    }
    return 0;
}


#pragma comment(linker, "/STACK:60000000")

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>

#define mems(a,x) memset(a,x,sizeof a)
using namespace std;
//type definitions
struct corpus
{
	int tin,tind,tout,toutd;
	corpus()
	{tin=0;tout=0;}
};
struct rez
{
	int fl,s,f;
};
//var definitions
int n,p,a,b,d;
vector<corpus> g;
vector<rez> ans;
//Function definitions
bool cmp(const rez &a,const rez &b)
{return a.s<b.s;}

int main()
{
	//freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	cin>>n>>p;
	g.resize(n+1);
	for (int i=1;i<=p;i++)
	{
		cin>>a>>b>>d;
		g[a].tout=b;
		g[a].toutd=d;
		g[b].tin=a;
		g[b].tind=d;
	}
	for (int i=1;i<=n;i++)
	{
		if (g[i].tin==0)
		{
			if (g[i].tout!=0)
			{
			int v=i;
			int push=g[i].toutd;
			do
			{
				push=min(push,g[v].toutd);
				v=g[v].tout;
			}
			while(g[v].tout!=0);
			rez r;
			r.fl=push;
			r.s=i;
			r.f=v;
			ans.push_back(r);
			}
		}
	}
	sort(ans.begin(),ans.end(),cmp);
	cout<<ans.size()<<endl;
	for (int i=0;i<ans.size();i++)
	{
		cout<<ans[i].s<<" "<<ans[i].f<<" "<<ans[i].fl<<endl;
	}
	return 0;
}


#pragma comment(linker, "/STACK:60000000")

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>

#define mems(a,x) memset(a,x,sizeof a)
using namespace std;
//type definitions
struct corpus
{
    int tin,tind,tout,toutd;
    corpus()
    {tin=0;tout=0;}
};
struct rez
{
    int fl,s,f;
};
//var definitions
int n,p,a,b,d;
vector<corpus> g;
vector<rez> ans;
//Function definitions
bool cmp(const rez &a,const rez &b)
{return a.fl>b.fl;}

int main()
{
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    cin>>n>>p;
    g.resize(n+1);
    for (int i=1;i<=p;i++)
    {
        cin>>a>>b>>d;
        g[a].tout=b;
        g[a].toutd=d;
        g[b].tin=a;
        g[b].tind=d;
    }
    for (int i=1;i<=n;i++)
    {
        if (g[i].tin==0)
        {
            if (g[i].tout!=0)
            {
            int v=i;
            int push=g[i].toutd;
            do
            {
                push=min(push,g[v].toutd);
                v=g[v].tout;
            }
            while(g[v].tout!=0);
            rez r;
            r.fl=push;
            r.s=i;
            r.f=v;
            ans.push_back(r);
            }
        }
    }
    sort(ans.begin(),ans.end(),cmp);
    cout<<ans.size()<<endl;
    for (int i=0;i<ans.size();i++)
    {
        cout<<ans[i].s<<" "<<ans[i].f<<" "<<ans[i].fl<<endl;
    }
    return 0;
}


#pragma comment(linker, "/STACK:60000000")

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>

#define mems(a,x) memset(a,x,sizeof a)
using namespace std;
//type definitions
struct corpus
{
	int tin,tind,tout,toutd;
	corpus()
	{tin=0;tout=0;}
};
struct rez
{
	int fl,s,f;
};
//var definitions
int n,p,a,b,d;
vector<corpus> g;
vector<rez> ans;
//Function definitions
bool cmp(const rez &a,const rez &b)
{return a.fl<b.fl;}

int main()
{
	//freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	cin>>n>>p;
	g.resize(n+1);
	for (int i=1;i<=p;i++)
	{
		cin>>a>>b>>d;
		g[a].tout=b;
		g[a].toutd=d;
		g[b].tin=a;
		g[b].tind=d;
	}
	for (int i=1;i<=n;i++)
	{
		if (g[i].tin==0)
		{
			if (g[i].tout!=0)
			{
			int v=i;
			int push=g[i].toutd;
			do
			{
				push=min(push,g[v].toutd);
				v=g[v].tout;
			}
			while(g[v].tout!=0);
			rez r;
			r.fl=push;
			r.s=i;
			r.f=v;
			ans.push_back(r);
			}
		}
	}
	sort(ans.begin(),ans.end(),cmp);
	cout<<ans.size()<<endl;
	for (int i=0;i<ans.size();i++)
	{
		cout<<ans[i].s<<" "<<ans[i].f<<" "<<ans[i].fl<<endl;
	}
	return 0;
}


#pragma comment(linker, "/STACK:60000000")

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>

#define mems(a,x) memset(a,x,sizeof a)
using namespace std;
//type definitions
struct corpus
{
    int tin,tind,tout,toutd;
    corpus()
    {tin=0;tout=0;}
};
struct rez
{
    int fl,s,f;
};
//var definitions
int n,p,a,b,d;
vector<corpus> g;
vector<rez> ans;
//Function definitions
bool cmp(const rez &a,const rez &b)
{return a.fl>b.fl;}

int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    cin>>n>>p;
    g.resize(n+1);
    for (int i=1;i<=p;i++)
    {
        cin>>a>>b>>d;
        g[a].tout=b;
        g[a].toutd=d;
        g[b].tin=a;
        g[b].tind=d;
    }
    for (int i=1;i<=n;i++)
    {
        if (g[i].tin==0)
        {
            if (g[i].tout!=0)
            {
            int v=i;
            int push=g[i].toutd;
            do
            {
                push=min(push,g[v].toutd);
                v=g[v].tout;
            }
            while(g[v].tout!=0);
            rez r;
            r.fl=push;
            r.s=i;
            r.f=v;
            ans.push_back(r);
            }
        }
    }
    sort(ans.begin(),ans.end(),cmp);
    cout<<ans.size()<<endl;
    for (int i=0;i<ans.size();i++)
    {
        cout<<ans[i].s<<" "<<ans[i].f<<" "<<ans[i].fl<<endl;
    }
    return 0;
}


#pragma comment(linker, "/STACK:60000000")

#include <iostream>
#include <stdio.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <algorithm>
#include <cstdlib>
#include <memory.h>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <time.h>
#include <string.h>
#include <cmath>
#include <iomanip>
#include <string>
#include <sstream>

#define mems(a,x) memset(a,x,sizeof a)
using namespace std;
//type definitions
struct corpus
{
	int in,ind,out,outd;
	corpus()
	{in=0;out=0;}
};
struct rez
{
	int fl,s,f;
};
//var definitions
int n,p,a,b,d;
vector<corpus> g;
vector<rez> ans;
//Function definitions
bool cmp(const rez &a,const rez &b)
{return a.fl>b.fl;}

int main()
{
	//freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	cin>>n>>p;
	g.resize(n+1);
	for (int i=1;i<=p;i++)
	{
		cin>>a>>b>>d;
		g[a].out=b;
		g[a].outd=d;
		g[b].in=a;
		g[b].ind=d;
	}
	for (int i=1;i<=n;i++)
	{
		if (g[i].in==0)
		{
			if (g[i].out!=0)
			{
			int v=i;
			int push=g[i].outd;
			do
			{
				push=min(push,g[v].outd);
				v=g[v].out;
			}
			while(g[v].out!=0);
			rez r;
			r.fl=push;
			r.s=i;
			r.f=v;
			ans.push_back(r);
			}
		}
	}
	sort(ans.begin(),ans.end(),cmp);
	cout<<ans.size()<<endl;
	for (int i=0;i<ans.size();i++)
	{
		cout<<ans[i].s<<" "<<ans[i].f<<" "<<ans[i].fl<<endl;
	}
	return 0;
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#define filename "farmer"
using namespace std;
const double PI = acos(-1.);

struct str {
	int a, b, d;
} q[1000];

int min(int a, int b) {return (a > b ? b : a);}
int max(int a, int b) {return (a > b ? a : b);}
int abs(int a) {return (a < 0 ? -a : a);}
void sort(str a[], int l, int r) ;

int main() {
//	freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
//	freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout);
	int n, a, b, c, k, kq, md;
	int down[1001]={}, d[1001]={}, up[1001]={};
	int f[1001]={};
	cin >> n >> k;
	for (int i=0; i<k; i++) {
		cin >> a >> b >> c;
		down[a] = b, up[b] = a;
		d[a] = c;
	}
	kq = 0;
	for (int i=1; i<=n; i++) {
		if (f[i]) continue;
		md = d[i];
		c = i;
		while (1) {
			if (f[c]) break;
			f[c] = 1;
//			cout << " //1 " << i << ' ' << c << ' ' << md << endl;
			if (down[c]) {
				if (d[c] < md) md = d[c];
				c = down[c];
			} else break;
		}
		if (down[c]) continue;
		q[kq].b = c;
		c = i;
		while (1) {
			f[c] = 1;
//			cout << " //2 " << i << ' ' << c << ' ' << md << endl;
			if (up[c]) {
				c = up[c];
				if (d[c] < md) md = d[c];
			} else break;
		}
		q[kq].a = c;
//		q[kq].d = md;
		q[kq].d = d[c];
//		kq++;
		if (q[kq].a != q[kq].b) kq++;
	}
	sort(q, 0, kq-1);
	cout << kq << endl;
	for (int i=0; i<kq; i++) {
		if (q[i].a == q[i].b) q[i].d = 1000000;
		cout << q[i].a << ' ' << q[i].b << ' ' << q[i].d << endl;
	}
//    system("pause");
    return 0;
}

void sort(str a[], int l, int r) {
	int i=l, j=r;
	str x, tmp;
	x = a[(l+r)/2];
	while (i < j) {
		while (a[i].a < x.a) i++;
		while (a[j].a > x.a) j--;
		if (i <= j) {
			tmp = a[i]; a[i] = a[j]; a[j] = tmp;
			i++; j--;
		}
	}
	if (j > l) sort(a, l, j);
	if (r > i) sort(a, i, r);
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#define filename "farmer"
using namespace std;
const double PI = acos(-1.);

struct str {
	int a, b, d;
} q[1000];

int min(int a, int b) {return (a > b ? b : a);}
int max(int a, int b) {return (a > b ? a : b);}
int abs(int a) {return (a < 0 ? -a : a);}
void sort(str a[], int l, int r) ;

int main() {
//	freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
//	freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout);
	int n, a, b, c, k, kq, md;
	int down[1001]={}, d[1001]={}, up[1001]={};
	int f[1001]={};
	cin >> n >> k;
	for (int i=0; i<k; i++) {
		cin >> a >> b >> c;
		down[a] = b, up[b] = a;
		d[a] = c;
	}
	kq = 0;
	for (int i=1; i<=n; i++) {
		if (f[i]) continue;
		md = d[i];
		c = i;
		while (1) {
			if (f[c]) break;
			f[c] = 1;
//			cout << " //1 " << i << ' ' << c << ' ' << md << endl;
			if (down[c]) {
				if (d[c] < md) md = d[c];
				c = down[c];
			} else break;
		}
		if (down[c]) continue;
		q[kq].b = c;
		c = i;
		while (1) {
			f[c] = 1;
//			cout << " //2 " << i << ' ' << c << ' ' << md << endl;
			if (up[c]) {
				c = up[c];
				if (d[c] < md) md = d[c];
			} else break;
		}
		q[kq].a = c;
		q[kq].d = md;
//		q[kq].d = d[c];
//		kq++;
		if (q[kq].a != q[kq].b) kq++;
	}
	sort(q, 0, kq-1);
	cout << kq << endl;
	for (int i=0; i<kq; i++) {
		if (q[i].a == q[i].b) q[i].d = 1000000;
		cout << q[i].a << ' ' << q[i].b << ' ' << q[i].d << endl;
	}
//    system("pause");
    return 0;
}

void sort(str a[], int l, int r) {
	int i=l, j=r;
	str x, tmp;
	x = a[(l+r)/2];
	while (i < j) {
		while (a[i].a < x.a) i++;
		while (a[j].a > x.a) j--;
		if (i <= j) {
			tmp = a[i]; a[i] = a[j]; a[j] = tmp;
			i++; j--;
		}
	}
	if (j > l) sort(a, l, j);
	if (r > i) sort(a, i, r);
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#define filename "farmer"
using namespace std;
const double PI = acos(-1.);

struct str {
	int a, b, d;
} q[1000];

int min(int a, int b) {return (a > b ? b : a);}
int max(int a, int b) {return (a > b ? a : b);}
int abs(int a) {return (a < 0 ? -a : a);}
void sort(str a[], int l, int r) ;

int main() {
//	freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
//	freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout);
	int n, a, b, c, k, kq, md;
	int down[1001]={}, d[1001]={}, up[1001]={};
	int f[1001]={};
	cin >> n >> k;
	for (int i=0; i<k; i++) {
		cin >> a >> b >> c;
		down[a] = b, up[b] = a;
		d[a] = c;
	}
	kq = 0;
	for (int i=1; i<=n; i++) {
		if (f[i]) continue;
		md = d[i];
		c = i;
		while (1) {
			if (f[c]) break;
			f[c] = 1;
//			cout << " //1 " << i << ' ' << c << ' ' << md << endl;
			if (down[c]) {
				if (d[c] < md) md = d[c];
				c = down[c];
			} else break;
		}
		if (down[c]) continue;
		q[kq].b = c;
		c = i;
		while (1) {
			f[c] = 1;
//			cout << " //2 " << i << ' ' << c << ' ' << md << endl;
			if (up[c]) {
				c = up[c];
				if (d[c] < md) md = d[c];
			} else break;
		}
		q[kq].a = c;
//		q[kq].d = md;
		q[kq].d = d[c];
		kq++;
//		if (q[kq].a != q[kq].b) kq++;
	}
	sort(q, 0, kq-1);
	cout << kq << endl;
	for (int i=0; i<kq; i++) {
		if (q[i].a == q[i].b) q[i].d = 1000000;
		cout << q[i].a << ' ' << q[i].b << ' ' << q[i].d << endl;
	}
//    system("pause");
    return 0;
}

void sort(str a[], int l, int r) {
	int i=l, j=r;
	str x, tmp;
	x = a[(l+r)/2];
	while (i < j) {
		while (a[i].a < x.a) i++;
		while (a[j].a > x.a) j--;
		if (i <= j) {
			tmp = a[i]; a[i] = a[j]; a[j] = tmp;
			i++; j--;
		}
	}
	if (j > l) sort(a, l, j);
	if (r > i) sort(a, i, r);
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#define filename "farmer"
using namespace std;
const double PI = acos(-1.);

struct str {
	int a, b, d;
} q[1000];

int min(int a, int b) {return (a > b ? b : a);}
int max(int a, int b) {return (a > b ? a : b);}
int abs(int a) {return (a < 0 ? -a : a);}
void sort(str a[], int l, int r) ;

int main() {
//	freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
//	freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout);
	int n, a, b, c, k, kq, md;
	int down[1001]={}, d[1001]={}, up[1001]={};
	int f[1001]={};
	cin >> n >> k;
	for (int i=0; i<k; i++) {
		cin >> a >> b >> c;
		down[a] = b, up[b] = a;
		d[a] = c;
	}
	kq = 0;
	for (int i=1; i<=n; i++) {
		if (f[i]) continue;
		md = 1000666;
		c = i;
		while (1) {
			if (f[c]) break;
			f[c] = 1;
			if (down[c]) {
				if (d[c] < md) md = d[c];
//				cout << c << ' ' << md <<endl;
				c = down[c];
			} else break;
		}
		if (down[c]) continue;
		q[kq].b = c;
		c = i;
		while (1) {
			f[c] = 1;
			if (up[c]) {
				c = up[c];
				if (d[c] < md) md = d[c];
//				cout << c << ' ' << md <<endl;
			} else break;
		}
		q[kq].a = c;
		q[kq].d = md;
//		q[kq].d = d[c];
		if (q[kq].a != q[kq].b) kq++;
	}
	sort(q, 0, kq-1);
	cout << kq << endl;
	for (int i=0; i<kq; i++) {
		cout << q[i].a << ' ' << q[i].b << ' ' << q[i].d << endl;
	}
//    system("pause");
    return 0;
}

void sort(str a[], int l, int r) {
	int i=l, j=r;
	str x, tmp;
	x = a[(l+r)/2];
	while (i < j) {
		while (a[i].a < x.a) i++;
		while (a[j].a > x.a) j--;
		if (i <= j) {
			tmp = a[i]; a[i] = a[j]; a[j] = tmp;
			i++; j--;
		}
	}
	if (j > l) sort(a, l, j);
	if (r > i) sort(a, i, r);
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#define filename "farmer"
using namespace std;
const double PI = acos(-1.);

struct str {
	int a, b, d;
} q[1000];

int min(int a, int b) {return (a > b ? b : a);}
int max(int a, int b) {return (a > b ? a : b);}
int abs(int a) {return (a < 0 ? -a : a);}
void sort(str a[], int l, int r) ;

int main() {
//	freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
//	freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout);
	int n, a, b, c, k, kq, md;
	int down[1001]={}, d[1001]={}, up[1001]={};
	int f[1001]={};
	cin >> n >> k;
	for (int i=0; i<k; i++) {
		cin >> a >> b >> c;
		down[a] = b, up[b] = a;
		d[a] = c;
	}
	kq = 0;
	for (int i=1; i<=n; i++) {
		if (f[i]) continue;
		md = d[i];
		c = i;
		while (1) {
			if (f[c]) break;
			f[c] = 1;
//			cout << " //1 " << i << ' ' << c << ' ' << md << endl;
			if (down[c]) {
				if (d[c] < md) md = d[c];
				c = down[c];
			} else break;
		}
		if (down[c]) continue;
		q[kq].b = c;
		c = i;
		while (1) {
			f[c] = 1;
//			cout << " //2 " << i << ' ' << c << ' ' << md << endl;
			if (up[c]) {
				c = up[c];
				if (d[c] < md) md = d[c];
			} else break;
		}
		q[kq].a = c;
		q[kq].d = md;
		kq++;
	}
	sort(q, 0, kq-1);
	cout << kq << endl;
	for (int i=0; i<kq; i++) {
		if (q[i].a == q[i].b) q[i].d = 1000000;
		cout << q[i].a << ' ' << q[i].b << ' ' << q[i].d << endl;
	}
//    system("pause");
    return 0;
}

void sort(str a[], int l, int r) {
	int i=l, j=r;
	str x, tmp;
	x = a[(l+r)/2];
	while (i < j) {
		while (a[i].a < x.a) i++;
		while (a[j].a > x.a) j--;
		if (i <= j) {
			tmp = a[i]; a[i] = a[j]; a[j] = tmp;
			i++; j--;
		}
	}
	if (j > l) sort(a, l, j);
	if (r > i) sort(a, i, r);
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#define filename "farmer"
using namespace std;
const double PI = acos(-1.);

struct str {
	int a, b, d;
} q[1000];

int min(int a, int b) {return (a > b ? b : a);}
int max(int a, int b) {return (a > b ? a : b);}
int abs(int a) {return (a < 0 ? -a : a);}
void sort(str a[], int l, int r) ;

int main() {
//	freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
//	freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout);
	int n, a, b, c, k, kq, md;
	int down[1001]={}, d[1001]={}, up[1001]={};
	int f[1001]={};
	cin >> n >> k;
	for (int i=0; i<k; i++) {
		cin >> a >> b >> c;
		down[a] = b, up[b] = a;
		d[a] = c;
	}
	kq = 0;
	for (int i=1; i<=n; i++) {
		if (f[i]) continue;
		md = d[i];
		c = i;
		while (1) {
			if (f[c]) break;
			f[c] = 1;
//			cout << " //1 " << i << ' ' << c << ' ' << md << endl;
			if (down[c]) {
				if (d[c] < md) md = d[c];
				c = down[c];
			} else break;
		}
		if (down[c]) continue;
		q[kq].b = c;
		c = i;
		while (1) {
			f[c] = 1;
//			cout << " //2 " << i << ' ' << c << ' ' << md << endl;
			if (up[c]) {
				c = up[c];
				if (d[c] < md) md = d[c];
			} else break;
		}
		q[kq].a = c;
		q[kq].d = md;
		kq++;
	}
	sort(q, 0, kq-1);
	cout << kq << endl;
	for (int i=0; i<kq; i++)
		cout << q[i].a << ' ' << q[i].b << ' ' << q[i].d << endl;
//    system("pause");
    return 0;
}

void sort(str a[], int l, int r) {
	int i=l, j=r;
	str x, tmp;
	x = a[(l+r)/2];
	while (i < j) {
		while (a[i].a < x.a) i++;
		while (a[j].a > x.a) j--;
		if (i <= j) {
			tmp = a[i]; a[i] = a[j]; a[j] = tmp;
			i++; j--;
		}
	}
	if (j > l) sort(a, l, j);
	if (r > i) sort(a, i, r);
}


#include <cstdlib>
#include <iostream>
#include <math.h>
#include <cstdio>
#include <algorithm>

using namespace std;

int a[2][1001];

int main() {

   int n, i, j, p, x, y, z, s, i1, min, flag;

  // freopen ("input.txt", "r", stdin);
  // freopen ("output.txt", "w", stdout);

  cin>>n>>p;
  if (p==0) cout<<0;
    else {

  for (i=1; i<=2; i++)
    for (j=1; j<=n; j++) a[i][j]=0;

   for (i=1; i<=p; i++) {
   cin>>x>>y>>z;
   a[2][x]=y;
   a[1][y]=z;
                       }

   s=0;

   for (i=1; i<=n; i++) if (a[1][i]==0) s++;
   cout<<s<<endl;

   for (i=1; i<=n; i++) if (a[1][i]==0) {
     i1=i;
     min=999999;
     while (a[2][i1]!=0) {
      if (a[1][a[2][i1]]<min) min=a[1][a[2][i1]];
      i1=a[2][i1];
           }
      cout<<i<<" "<<i1<<" "<<min<<endl;
       }
    }
cin.get(); cin.get();
//  return 0;
    }


#include <cstdlib>
#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    int q, n, a[101],b[101],c[101],d[101],e[101], i, j, min;

  //  freopen ("input.txt", "r", stdin);
  //  freopen ("output.txt", "w", stdout);

    cin>>n;
    for (i=1; i<=n; i++) {
      cin>>a[i]>>b[i]>>c[i]>>d[i];
      e[i]=1;
        }
    for (i=1; i<=n; i++)
      for (j=1; j<=n; j++) if ((a[i]<a[j]) && (b[i]<b[j]) && (c[i]<c[j])) e[i]=0;

   min=100500;
    for (i=1; i<=n; i++) if ((d[i]<min) && (e[i]!=0)) {
        min=d[i];
        q=i;
                                                      }
    cout<<q;
    cin.get(); cin.get();

    }


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
#include <map>

using namespace std;

int main(){
    int i, j, k, n, z, z1, total, total1, n1, a1, b, c, c1;
    cin >> n >> n1;
    int a[n+1][n+1];
    for(i = 0; i <= n; i++){
          for(j = 0; j <= n; j++)
               a[i][j] = 1000000000;
    }
    vector <int> v, v1, v2, v3, v4, v5, v6;
    for(i = 0; i < n1; i++){
          cin >> a1 >> b >> c;
          a[a1][b] = c;
          v.push_back(a1);
          v1.push_back(b);
    }
    for(j = 1; j <= n; j++){
          z = 0;
          z1 = 0;
    for(i = 0; i < n1; i++){
          if(v[i] == j)
               z1 = 1;
          if(v1[i] == j)
               z = 1;
    }
    if(z1 == 1 && z == 0)
        v2.push_back(j);
    else if(z1 == 0 && z == 1)
         v3.push_back(j);
    }
    sort(v2.begin(), v2.end());
    if(v2.size() == 0 || v3.size() == 0)
         cout << "0" << endl;
    else{
    for(i = 0; i < v2.size(); i++){
          c = v2[i];
          z = 1;
          k = 0;
          total1 = 1000000000;
         while(z != 0){
                 z = 0;
                 c1 = c;
         for(j = 0; j <= n; j++){
               if(a[c][j] != 1000000000){
                        c = j;
                        z = 1;
                        k = 1;
                        break;
               }
         }
         if(k == 1) {
              total = a[c1][c];
              if(total < total1)
                  total1 = total;
         }
         }
         v4.push_back(v2[i]);
         v5.push_back(c);
         v6.push_back(total1);
    }
        cout << v4.size() << endl;
    for(i = 0; i < v4.size(); i++)
          cout << v4[i] << " " << v5[i] << " " << v6[i] << endl;
    }
    //system("pause");
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
#include <map>

using namespace std;

int main(){
    int i, j, k, n, z, z1, total, total1, n1, a1, b, c;
    cin >> n >> n1;
    int a[n+1][n+1];
    for(i = 0; i <= n; i++){
          for(j = 0; j <= n; j++)
               a[i][j] = 1000000000;
    }
    vector <int> v, v1, v2, v4, v5, v6;
    for(i = 0; i < n1; i++){
          cin >> a1 >> b >> c;
          a[a1][b] = c;
          v.push_back(a1);
          v1.push_back(b);
    }
    for(j = 1; j <= n; j++){
          z = 0;
          z1 = 0;
    for(i = 0; i < n1; i++){
          if(v[i] == j)
               z1 = 1;
          if(v1[i] == j)
               z = 1;
    }
    if(z1 == 1 && z == 0)
        v2.push_back(j);
    }
    sort(v2.begin(), v2.end());
    if(v2.size() == 0)
         cout << "0" << endl;
    else{
    for(i = 0; i < v2.size(); i++){
          c = v2[i];
          z = 1;
          k = 0;
          total1 = 100000000;
         while(z != 0){
                 z = 0;
         for(j = 0; j <= n; j++){
               if(a[c][j] != 1000000000){
                        c = j;
                        z = 1;
                        k = 1;
                        break;
               }
         }
         if(k == 1) {
              total = a[v2[i]][c];
              if(total < total1)
                  total1 = total;
         }
         }
         v4.push_back(v2[i]);
         v5.push_back(c);
         v6.push_back(total1);
    }
        cout << v4.size() << endl;
    for(i = 0; i < v4.size(); i++)
          cout << v4[i] << " " << v5[i] << " " << v6[i] << endl;
    }
    //system("pause");
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
#include <map>

using namespace std;

int main(){
    int i, j, k, n, z, z1, total, total1, n1, a1, b, c;
    cin >> n >> n1;
    int a[n+1][n+1];
    for(i = 0; i <= n; i++){
          for(j = 0; j <= n; j++)
               a[i][j] = 1000000000;
    }
    vector <int> v, v1, v2, v3, v4, v5, v6;
    for(i = 0; i < n1; i++){
          cin >> a1 >> b >> c;
          a[a1][b] = c;
          v.push_back(a1);
          v1.push_back(b);
    }
    for(j = 1; j <= n; j++){
          z = 0;
          z1 = 0;
    for(i = 0; i < n1; i++){
          if(v[i] == j)
               z1 = 1;
          if(v1[i] == j)
               z = 1;
    }
    if(z1 == 1 && z == 0)
        v2.push_back(j);
    else if(z1 == 0 && z == 1)
         v3.push_back(j);
    }
    sort(v2.begin(), v2.end());
    if(v2.size() == 0 || v3.size() == 0)
         cout << "0" << endl;
    else{
    for(i = 0; i < v2.size(); i++){
          c = v2[i];
          z = 1;
          k = 0;
          total1 = 100000000;
         while(z != 0){
                 z = 0;
         for(j = 0; j <= n; j++){
               if(a[c][j] != 1000000000){
                        c = j;
                        z = 1;
                        k = 1;
                        break;
               }
         }
         if(k == 1) {
              total = a[v2[i]][c];
              if(total < total1)
                  total1 = total;
         }
         }
         v4.push_back(v2[i]);
         v5.push_back(c);
         v6.push_back(total1);
    }
        cout << v4.size() << endl;
    for(i = 0; i < v4.size(); i++)
          cout << v4[i] << " " << v5[i] << " " << v6[i] << endl;
    }
    //system("pause");
    return 0;
}


#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <cmath>
#include <sstream>
#include <map>
#include <set>
#include <numeric>
#include <memory.h>
#include <cstdio>
#include <assert.h>

using namespace std;

#define pb push_back
#define INF 1011111111
#define FOR(i,a,b) for (int _n(b), i(a); i < _n; i++)
#define rep(i,n) FOR(i,0,n)
#define ford(i,a,b) for(int i=(a),_b=(b);i>=_b;--i)
#define CL(a,v) memset((a),(v),sizeof(a))
#define mp make_pair
#define X first
#define Y second
#define all(c) (c).begin(), (c).end()
#define SORT(c) sort(all(c))

typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> pii;

VI head, nxt, out, d, istank, istap;
int n;

pii dfs(int v, int f=-1)
{
    pii ans = mp(v,INF);
    for(int i = head[v]; i >= 0; i = nxt[i])
    {
        if(out[i] == f) continue;
        ans.Y = min(ans.Y, d[i]);
        pii res = dfs(out[i], v);
        ans.Y = min(ans.Y, res.Y);
        ans.X = res.X;
    }
    return ans;
}

int main()
{
	#ifndef ONLINE_JUDGE
        freopen("input.txt","r",stdin);
        //freopen("output.txt","w",stdout);
	#endif

    int p;
    cin >> n >> p;

    head.resize(n,-1), nxt.resize(p), out.resize(p), d.resize(p), istank.resize(n,1), istap.resize(n,1);

    rep(i,p)
    {
        int a,b,c;
        cin >> a >> b >> c;
        --a, --b;

        istank[b] = 0;
        istap[a] = 0;
        nxt[i] = head[a];
        head[a] = i;
        out[i] = b;
        d[i] = c;
    }

    if(count(all(istank),1) != count(all(istap),1))
    {
        cout << 0 << endl;
        return 0;
    }

    map< int, pii > ret;

    rep(i,n) if(istank[i])
    {
        ret[i] = dfs(i);

        if(ret[i].X == i)
        {
            cout << 0 << endl;
            return 0;
        }
    }

    cout << ret.size() << endl;

    for(map< int, pii > :: iterator it = ret.begin(); it != ret.end(); ++it)
    {
        cout << it->X+1 << ' ' << it->Y.X+1 << ' ' << it->Y.Y << endl;
    }

	return 0;
}


#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <cmath>
#include <sstream>
#include <map>
#include <set>
#include <numeric>
#include <memory.h>
#include <cstdio>
#include <assert.h>

using namespace std;

#define pb push_back
#define INF 1011111111
#define FOR(i,a,b) for (int _n(b), i(a); i < _n; i++)
#define rep(i,n) FOR(i,0,n)
#define ford(i,a,b) for(int i=(a),_b=(b);i>=_b;--i)
#define CL(a,v) memset((a),(v),sizeof(a))
#define mp make_pair
#define X first
#define Y second
#define all(c) (c).begin(), (c).end()
#define SORT(c) sort(all(c))

typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> pii;

VI head, nxt, out, d, istank, istap;
int n;

pii dfs(int v, int f=-1)
{
    pii ans = mp(v,INF);
    for(int i = head[v]; i >= 0; i = nxt[i])
    {
        if(out[i] == f) continue;
        ans.Y = min(ans.Y, d[i]);
        pii res = dfs(out[i], v);
        ans.Y = min(ans.Y, res.Y);
        ans.X = res.X;
    }
    return ans;
}

int main()
{
	#ifndef ONLINE_JUDGE
        freopen("input.txt","r",stdin);
        //freopen("output.txt","w",stdout);
	#endif

    int p;
    cin >> n >> p;

    head.resize(n,-1), nxt.resize(p), out.resize(p), d.resize(p), istank.resize(n,1), istap.resize(n,1);

    rep(i,p)
    {
        int a,b,c;
        cin >> a >> b >> c;
        --a, --b;

        istank[b] = 0;
        istap[a] = 0;
        nxt[i] = head[a];
        head[a] = i;
        out[i] = b;
        d[i] = c;
    }

    if(count(all(istank),1) != count(all(istap),1))
    {
        cout << 0 << endl;
        return 0;
    }

    map< int, pii > ret;

    rep(i,n) if(istank[i])
    {
        ret[i] = dfs(i);
    }

    if(count(all(istank),1) != ret.size())
    {
        cout << 0 << endl;
        return 0;
    }

    cout << ret.size() << endl;

    for(map< int, pii > :: iterator it = ret.begin(); it != ret.end(); ++it)
    {
        cout << it->X+1 << ' ' << it->Y.X+1 << ' ' << it->Y.Y << endl;
    }

	return 0;
}


#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <cmath>
#include <sstream>
#include <map>
#include <set>
#include <numeric>
#include <memory.h>
#include <cstdio>
#include <assert.h>

using namespace std;

#define pb push_back
#define INF 1011111111
#define FOR(i,a,b) for (int _n(b), i(a); i < _n; i++)
#define rep(i,n) FOR(i,0,n)
#define ford(i,a,b) for(int i=(a),_b=(b);i>=_b;--i)
#define CL(a,v) memset((a),(v),sizeof(a))
#define mp make_pair
#define X first
#define Y second
#define all(c) (c).begin(), (c).end()
#define SORT(c) sort(all(c))

typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> pii;

VI head, nxt, out, d, istank;
int n;

pii dfs(int v, int f=-1)
{
    pii ans = mp(v,INF);
    for(int i = head[v]; i >= 0; i = nxt[i])
    {
        if(out[i] == f) continue;
        ans.Y = min(ans.Y, d[i]);
        pii res = dfs(out[i], v);
        ans.Y = min(ans.Y, res.Y);
        ans.X = res.X;
    }
    return ans;
}

int main()
{
	#ifndef ONLINE_JUDGE
        freopen("input.txt","r",stdin);
        //freopen("output.txt","w",stdout);
	#endif

    int p;
    cin >> n >> p;

    head.resize(n,-1), nxt.resize(p), out.resize(p), d.resize(p), istank.resize(n,1);

    rep(i,p)
    {
        int a,b,c;
        cin >> a >> b >> c;
        --a, --b;

        istank[b] = 0;
        nxt[i] = head[a];
        head[a] = i;
        out[i] = b;
        d[i] = c;
    }

    map< int, pii > ret;

    rep(i,n) if(istank[i])
    {
        ret[i] = dfs(i);
    }

    cout << ret.size() << endl;

    for(map< int, pii > :: iterator it = ret.begin(); it != ret.end(); ++it)
    {
        cout << it->X+1 << ' ' << it->Y.X+1 << ' ' << it->Y.Y << endl;
    }

	return 0;
}


#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <cmath>
#include <sstream>
#include <map>
#include <set>
#include <numeric>
#include <memory.h>
#include <cstdio>
#include <assert.h>

using namespace std;

#define pb push_back
#define INF 1011111111
#define FOR(i,a,b) for (int _n(b), i(a); i < _n; i++)
#define rep(i,n) FOR(i,0,n)
#define ford(i,a,b) for(int i=(a),_b=(b);i>=_b;--i)
#define CL(a,v) memset((a),(v),sizeof(a))
#define mp make_pair
#define X first
#define Y second
#define all(c) (c).begin(), (c).end()
#define SORT(c) sort(all(c))

typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> pii;

VI head, nxt, out, d, istank, istap;
int n;

pii dfs(int v, int f=-1)
{
    pii ans = mp(v,INF);
    for(int i = head[v]; i >= 0; i = nxt[i])
    {
        if(out[i] == f) continue;
        ans.Y = min(ans.Y, d[i]);
        pii res = dfs(out[i], v);
        ans.Y = min(ans.Y, res.Y);
        ans.X = res.X;
    }
    return ans;
}

int main()
{
	#ifndef ONLINE_JUDGE
        freopen("input.txt","r",stdin);
        //freopen("output.txt","w",stdout);
	#endif

    int p;
    cin >> n >> p;

    head.resize(n,-1), nxt.resize(p), out.resize(p), d.resize(p), istank.resize(n,1), istap.resize(n,1);

    rep(i,p)
    {
        int a,b,c;
        cin >> a >> b >> c;
        --a, --b;

        istank[b] = 0;
        istap[a] = 0;
        nxt[i] = head[a];
        head[a] = i;
        out[i] = b;
        d[i] = c;
    }

    if(count(all(istank),1) != count(all(istap),1))
    {
        cout << 0 << endl;
        return 0;
    }

    map< int, pii > ret;

    rep(i,n) if(istank[i])
    {
        ret[i] = dfs(i);
    }

    if(count(all(istank),1) != ret.size() || count(all(istank),1) < 2*ret.size())
    {
        cout << 0 << endl;
        return 0;
    }

    cout << ret.size() << endl;

    for(map< int, pii > :: iterator it = ret.begin(); it != ret.end(); ++it)
    {
        cout << it->X+1 << ' ' << it->Y.X+1 << ' ' << it->Y.Y << endl;
    }

	return 0;
}


#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <cmath>
#include <sstream>
#include <map>
#include <set>
#include <numeric>
#include <memory.h>
#include <cstdio>
#include <assert.h>

using namespace std;

#define pb push_back
#define INF 1011111111
#define FOR(i,a,b) for (int _n(b), i(a); i < _n; i++)
#define rep(i,n) FOR(i,0,n)
#define ford(i,a,b) for(int i=(a),_b=(b);i>=_b;--i)
#define CL(a,v) memset((a),(v),sizeof(a))
#define mp make_pair
#define X first
#define Y second
#define all(c) (c).begin(), (c).end()
#define SORT(c) sort(all(c))

typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> pii;

VI head, nxt, out, d, istank, istap;
int n;

pii dfs(int v, int f=-1)
{
    pii ans = mp(v,INF);
    for(int i = head[v]; i >= 0; i = nxt[i])
    {
        if(out[i] == f) continue;
        ans.Y = min(ans.Y, d[i]);
        pii res = dfs(out[i], v);
        ans.Y = min(ans.Y, res.Y);
        ans.X = res.X;
    }
    return ans;
}

int main()
{
	#ifndef ONLINE_JUDGE
        freopen("input.txt","r",stdin);
        //freopen("output.txt","w",stdout);
	#endif

    int p;
    cin >> n >> p;

    head.resize(n,-1), nxt.resize(p), out.resize(p), d.resize(p), istank.resize(n,1), istap.resize(n,1);

    rep(i,p)
    {
        int a,b,c;
        cin >> a >> b >> c;
        --a, --b;

        istank[b] = 0;
        istap[a] = 0;
        nxt[i] = head[a];
        head[a] = i;
        out[i] = b;
        d[i] = c;
    }

//    if(count(all(istank),1) != count(all(istap),1))
//    {
//        cout << 0 << endl;
//        return 0;
//    }

    map< int, pii > ret;

    rep(i,n) if(istank[i])
    {
        pii r = dfs(i);

        if(r.X == i) continue;

        ret[i] = r;
//        {
//            cout << 0 << endl;
//            return 0;
//        }
    }

    cout << ret.size() << endl;

    for(map< int, pii > :: iterator it = ret.begin(); it != ret.end(); ++it)
    {
        cout << it->X+1 << ' ' << it->Y.X+1 << ' ' << it->Y.Y << endl;
    }

	return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
using namespace std;

int prior[256];
vector<char> var;
vector<string> formuls;
const int add = 10;

bool get(char c) {
     for(int i = 0; i < var.size(); ++i)
             if(var[i] == c)
                       return true;
     return false;
}

bool is_letter(char c) {
     return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

bool func(char type, bool a, bool b = 0) {
     if(type == '+')
             return a || b;
     if(type == '*')
             return a && b;
     if(type == '!')
             return !a;
     if(type == '~')
             return (a == 1 && b == 0 ? 0 : 1);
     if(type == '=')
             return (a == b ? 1 : 0);
     if(type == '$')
             return (a == b ? 0 : 1);
}

void Init() {
     for(int i = 0; i < 256; ++i)
             prior[i] = 0;
     prior['!'] = 4;
     prior['*'] = 3;
     prior['$']  = prior['+'] = 2;
     prior['='] = prior['~'] = 1;
}

string Copy(string s, int l, int r) {
       string res = "";
       for(int i = l; i <= r; ++i)
               res += s[i];
       return res;
}

bool ok_brackets(string s) {
     int n = s.length();
     if(s[0] != '(' || s[n - 1] != ')')
             return true;
     int balance = 0;
     for(int i = 0; i < n - 1; ++i) {
             if(s[i] == '(')
                     ++balance;
             if(s[i] == ')')
                     --balance;
             if(!balance)
                         return true;
     }
     return false;
}

string delete_brackets(string s) {
     if(!ok_brackets(s))
                        return Copy(s, 1, s.length() - 2);
}

struct node {
       bool val;
       char oprt;
       int pos;
       node* left, *right;
};

node* build(string s) {
      while(!ok_brackets(s))
                            s = delete_brackets(s);
      node* root = (node*)malloc(sizeof(root));
      formuls.push_back(s);
      root->pos = formuls.size() - 1;
      if(s.length() == 1) {
                    if(!get(s[0]))
                                      var.push_back(s[0]);
                    root->oprt = s[0];
                    root->left = root->right = NULL;
                    return root;
      }
      int minPr = 100, cur = 0, n = s.length();
      for(int i = 0; i < n; ++i) {
              if(s[i] == '(')
                      cur += add;
              if(s[i] == ')')
                      cur -= add;
              if(!is_letter(s[i]) && s[i] != '(' && s[i] != ')')
                                  minPr = min(cur + prior[s[i]], minPr);
      }
      int split = -1;
      for(int i = 0; i < n; ++i) {
              if(s[i] == '(')
                      cur += add;
              if(s[i] == ')')
                      cur -= add;
              if(!is_letter(s[i]) && s[i] != '(' && s[i] != ')' && cur + prior[s[i]] == minPr)
                                  split = i;
      }
      root->oprt = s[split];
      string L = Copy(s, 0, split - 1), R = Copy(s, split + 1, n - 1);
      if(root->oprt == '!') {
                    root->right = NULL;
                    root->left = build(R);
      }
      else {
          root->left = build(L);
          root->right = build(R);
      }
      return root;
}

/*void print(node* root) {
     cout << formuls[root->pos] << endl;
     if(root->left)
                   print(root->left);
     if(root->right)
                    print(root->right);
}*/

//void solve(bool values[256]) {

int main() {
    cout << "+ - or" << endl << "! - not" << endl << "* - and" << endl<< "~ - implication" << endl
         <<"$ - xor" << endl << "= - equal" << endl;

    string s;
    getline(cin, s);
    while(s.find(' ') < s.length())
                   s.erase(s.find(' '), 1);
    Init();
    node* global_root;
    global_root = build(s);
    cout << var.size();
    cin >> s;
    return 0;
}


#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
#include <algorithm>
using namespace std;

int g[1000][1000];
vector<bool> u(1000, false);
int n;

struct ans {
       int from, to, d;
       ans(int a, int b, int c): from(a), to(b), d(c) {}
};

vector<ans> a;

void dfs(int v, int minD, int start) {
     u[v] = true;
     bool done = false;
     for(int i = 0; i < n; ++i)
             if(g[v][i] > 0 && !u[i]) {
                        done = true;
                        dfs(i, min(minD, g[v][i]), start);
             }
     if(!done)
               a.push_back(ans(start + 1, v + 1, minD));
}

int main() {
   int m;

   cin >> n >> m;

   for(int i = 0; i < n; ++i)
           for(int j = 0; j < n; ++j)
                   g[i][j] = -1;

   vector<bool> s(n, false);
   vector<bool> is(n, false);

   for(int i = 0; i < m; ++i) {
           int t, b, d;
           cin >> t >> b >> d;
           --t;
           --b;
           s[b] = true;
           is[t] = true;
           g[t][b] = d;
   }

   for(int i = 0; i < n; ++i)
           if(!u[i] && is[i] && !s[i])
                    dfs(i, 1000 * 1000 + 1, i);

   cout << a.size() << endl;
   for(int i = 0; i < a.size(); ++i)
           cout << a[i].from << " " << a[i].to << " " << a[i].d << endl;

   cin >> n;

   return 0;
}


#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
#include <algorithm>
using namespace std;

vector<vector<pair<int, int> > > g(1000);
vector<bool> u(1000, false);

struct ans {
       int from, to, d;
       ans(int a, int b, int c): from(a), to(b), d(c) {}
};

vector<ans> a;

void dfs(int v, int minD, int start) {
     u[v] = true;
     bool done = false;
     for(int i = 0; i < g[v].size(); ++i) {
             int to = g[v][i].first;
             if(!u[to])
                       dfs(to, min(minD, g[v][i].second), start);
             done = true;
     }
     if(!done && v != start)
               a.push_back(ans(start + 1, v + 1, minD));
}

int main() {
   int n, m;

   cin >> n >> m;

   for(int i = 0; i < m; ++i) {
           int a, b, d;
           cin >> a >> b >> d;
           --a, --b;
           g[a].push_back(pair<int, int>(b, d));
   }

   for(int i = 0; i < n; ++i)
           if(!u[i])
                    dfs(i, 1000 * 1000 + 1, i);

   cout << a.size() << endl;
   for(int i = 0; i < a.size(); ++i)
           cout << a[i].from << " " << a[i].to << " " << a[i].d << endl;

   cin >> n;

   return 0;
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int dcnhan[1001]={0},dccho[1001]={0};
    pair<int,int> dscho[1001],dsnhan[1001];
    int m,c,n,gt;
    cin>>n>>m;
    for (int i=0;i<m;i++)
    {
        cin>>c>>n>>gt;
        dcnhan[n]=gt;
        dccho[c]=gt;
    }
    int sl=0,sl2=0;
    for (int i=1;i<=n;i++)
    {
        if (dcnhan[i]==0)
        {
            sl++;
           dsnhan[sl].first=dccho[i];
           dsnhan[sl].second=i;
        }
        if (dccho[i]==0)
        {
            sl2=0;
            dscho[sl].first=dcnhan[i];
            dscho[sl].second=i;
        }
    }
    sort(dsnhan,dsnhan+sl);
    sort(dscho,dscho+sl);
    cout<<sl<<endl;
    for (int i=1;i<=sl;i++)
    {
        cout<<dsnhan[i].second<<" "<<dscho[i].second<<" "<<min(dscho[i].first,dsnhan[i].first)<<endl;
    }
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int dcnhan[1001]={0},dccho[1001]={0};
  //  pair<int,int> dscho[1001],dsnhan[1001];
    int dslk[1001]={0};
    int m,c,n,gt,t;
    cin>>n>>m;
    for (int i=0;i<m;i++)
    {
        cin>>c>>t>>gt;
        dcnhan[t]=gt;
        dccho[c]=gt;
        dslk[c]=t;
    }
    int dc=0,j;
    for (int i=1;i<=n;i++)
    {
        if (dcnhan[i]==0&&dccho[i]!=0)
        dc++;
    }
        cout<<dc<<endl;
    for (int i=1;i<=n;i++)
    {
        if (dcnhan[i]==0&&dccho[i]!=0)
        {
            cout<<i<<" ";
            dc=dccho[i];
            j=i;
            while (dslk[j]!=0)
            {
                j=dslk[j];
                dc=min(dc,dcnhan[j]);
            }
            cout<<j<<" "<<min(dcnhan[j],dc)<<endl;
        }
    }
       /* if (dcnhan[i]==0)
        {
            sl++;
           dsnhan[sl].first=dccho[i];
           dsnhan[sl].second=i;
        }
        if (dccho[i]==0)
        {
            sl2++;
            dscho[sl2].first=dcnhan[i];
            dscho[sl2].second=i;
        }*/
    //sort(dsnhan,dsnhan+sl);
    //sort(dscho,dscho+sl);
    //cout<<sl<<endl;

    /*for (int i=1;i<=sl;i++)
    {
        cout<<dsnhan[i].first<<" "<<dsnhan[i].second<<endl;
        cout<<dscho[i].first<<" "<<dscho[i].second<<endl;
        //cout<<dsnhan[i].second<<" "<<dscho[i].second<<" "<<min(dscho[i].first,dsnhan[i].first)<<endl;
    }*/
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int dcnhan[1001]={0},dccho[1001]={0};
  //  pair<int,int> dscho[1001],dsnhan[1001];
    int dslk[1001]={0};
    int m,c,n,gt,t;
    cin>>n>>m;
    for (int i=0;i<m;i++)
    {
        cin>>c>>t>>gt;
        dcnhan[t]=gt;
        dccho[c]=gt;
        dslk[c]=t;
    }
    int dc=0,j;
    for (int i=1;i<=n;i++)
    {
        if (dcnhan[i]==0)
        dc++;
    }
        cout<<dc<<endl;
    for (int i=1;i<=n;i++)
    {
        if (dcnhan[i]==0)
        {
            cout<<i<<" ";
            dc=dccho[i];
            j=i;
            while (dslk[j]!=0)
            {
                j=dslk[j];
            }
            cout<<j<<" "<<min(dcnhan[j],dc)<<endl;
        }
    }
       /* if (dcnhan[i]==0)
        {
            sl++;
           dsnhan[sl].first=dccho[i];
           dsnhan[sl].second=i;
        }
        if (dccho[i]==0)
        {
            sl2++;
            dscho[sl2].first=dcnhan[i];
            dscho[sl2].second=i;
        }*/
    //sort(dsnhan,dsnhan+sl);
    //sort(dscho,dscho+sl);
    //cout<<sl<<endl;

    /*for (int i=1;i<=sl;i++)
    {
        cout<<dsnhan[i].first<<" "<<dsnhan[i].second<<endl;
        cout<<dscho[i].first<<" "<<dscho[i].second<<endl;
        //cout<<dsnhan[i].second<<" "<<dscho[i].second<<" "<<min(dscho[i].first,dsnhan[i].first)<<endl;
    }*/
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int dcnhan[1001]={0},dccho[1001]={0};
  //  pair<int,int> dscho[1001],dsnhan[1001];
    int dslk[1001]={0};
    int m,c,n,gt,t;
    cin>>n>>m;
    for (int i=0;i<m;i++)
    {
        cin>>c>>t>>gt;
        dcnhan[t]=gt;
        dccho[c]=gt;
        dslk[c]=t;
    }
    int dc=0,j;
    for (int i=1;i<=n;i++)
    {
        if (dcnhan[i]==0&&dccho[i]!=0)
        dc++;
    }
        cout<<dc<<endl;
    for (int i=1;i<=n;i++)
    {
        if (dcnhan[i]==0&&dccho[i]!=0)
        {
            cout<<i<<" ";
            dc=dccho[i];
            j=i;
            while (dslk[j]!=0)
            {
                j=dslk[j];
            }
            cout<<j<<" "<<min(dcnhan[j],dc)<<endl;
        }
    }
       /* if (dcnhan[i]==0)
        {
            sl++;
           dsnhan[sl].first=dccho[i];
           dsnhan[sl].second=i;
        }
        if (dccho[i]==0)
        {
            sl2++;
            dscho[sl2].first=dcnhan[i];
            dscho[sl2].second=i;
        }*/
    //sort(dsnhan,dsnhan+sl);
    //sort(dscho,dscho+sl);
    //cout<<sl<<endl;

    /*for (int i=1;i<=sl;i++)
    {
        cout<<dsnhan[i].first<<" "<<dsnhan[i].second<<endl;
        cout<<dscho[i].first<<" "<<dscho[i].second<<endl;
        //cout<<dsnhan[i].second<<" "<<dscho[i].second<<" "<<min(dscho[i].first,dsnhan[i].first)<<endl;
    }*/
}