#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<string.h>

#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
#define NDEBUG
#define eprintf(...) do {} while (0)
#endif
#include<cassert>

using namespace std;

typedef long long LL;
typedef vector<int> VI;

#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define EACH(i,c) for(__typeof((c).begin()) i=(c).begin(),i##_end=(c).end();i!=i##_end;++i)

template<class T> inline void amin(T &x, const T &y) { if (y<x) x=y; }
template<class T> inline void amax(T &x, const T &y) { if (x<y) x=y; }
#define rprintf(fmt, begin, end) do { const auto end_rp = (end); auto it_rp = (begin); for (bool sp_rp=0; it_rp!=end_rp; ++it_rp) { if (sp_rp) putchar(' '); else sp_rp = true; printf(fmt, *it_rp); } putchar('\n'); } while(0)

int N, M;
vector<pair<int, int> > G[100011];

VI que;
bool vis[100011];
int ans[100011];

void MAIN() {
    scanf("%d%d", &N, &M);
    REP (i, M) {
	int x, y, c;
	scanf("%d%d%d", &x, &y, &c);
	x--; y--;
	G[x].emplace_back(y, c);
	G[y].emplace_back(x, c);
    }

    que.push_back(0);
    vis[0] = true;
    ans[0] = 1;
    REP (i, N) {
	int v = que[i];
	EACH (e, G[v]) if (!vis[e->first]) {
	    int w = e->first;
	    vis[w] = true;
	    que.push_back(w);

	    if (ans[v] == e->second) {
		ans[w] = ans[v] + 1;
		if (ans[w] > N) ans[w] = 1;
	    } else {
		ans[w] = e->second;
	    }
	}
    }

    REP (i, N) printf("%d\n", ans[i]);
}

int main() {
    int TC = 1;
//    scanf("%d", &TC);
    REP (tc, TC) MAIN();
    return 0;
}


#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define rep(i,N) for(int i = 0;i < N;++i)
#define rep1(i,N) for(int i = 1;i < N;++i)
#define co(x) cout << x << endl
#define cosp(x) cout << x << " "
using ll = long long;
using ull = unsigned long long;
int sub(int N){
    vector<char>n;
    string c = to_string(N);
    for(int i = 0;i < c.length();i++) n.push_back(c[i]);
    sort(n.begin(),n.end());
    int a = 0,b = 0;
    for(int i = 0;i < n.size();i++){
        a += (int)n[i] - '0';
        if(i != n.size()-1) a *= 10;
    }
    reverse(n.begin(),n.end());
    for(int i = 0;i < n.size();i++){
        b += (int)n[i] - '0';
        if(i != n.size()-1) b *= 10;
    }
    a = b-a;
    return a;
}
int main(){
int N;
int K;
cin >> N >> K;
int a = N;
rep(i,K){
    a = sub(a);
}
co(a);
}