#include <bits/stdc++.h>

using namespace std;

#define int long long
#define mp make_pair
#define pb push_back
#define ALL(A) A.begin(),A.end()
#define RALL(A) A.rbegin(),A.rend()
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define RFOR(i,a,b) for(int i=(a);i>=(b);i--)
#define SZ(A) A.size()

vector<vector<pair<int,int> > > g((int)1e5 + 1);
vector<map<int,int> > gt((int)1e5+1);

void dfs(int v,int c = 1,int pr = -1,int cur = 0)
{
    if(c == 2)
    {
        for(auto x : g[v])
        {
            cur += x.second;
            if(gt[pr].count(x.first))
                gt[pr][x.first] = min(gt[pr][x.first],cur*cur);
            else
                gt[pr][x.first] = cur * cur;
            cur -= x.second;
        }
        return;
    }
    for(auto x : g[v])
    {
        dfs(x.first,c+1,v,x.second);
    }
    return;
}

void solve_case()
{
    int n,m;
    cin >> n >> m;

    int a,b,c;

    for(int i = 0; i < m; i++)
    {
        cin >> a >> b >> c;
        g[a].pb(mp(b,c));
        g[b].pb(mp(a,c));
    }

    for(int i = 1; i <= n; i++)
    {
        dfs(i);
    }

    vector<int> d(n+1,(int)1e18);

    d[1] = 0;

    set<pair<int,int> > q;

    q.insert(mp(d[1],1));

    int v;

    int to,len;

    while(!q.empty())
    {
        v = q.begin()->second;
        q.erase(q.begin());
        for(auto x : gt[v])
        {
            to = x.first, len = x.second;
            if(d[to] > d[v] + len)
            {
                q.erase(mp(d[to],to));
                d[to] = d[v] + len;
                q.insert(mp(d[to],to));
            }
        }
    }

    for(int i = 1; i <= n; i++)
        cout << (d[i] == (int)1e18 ? -1 : d[i]) << " ";

    return;
}

signed main()
{
    ios::sync_with_stdio(0); cin.tie(nullptr); cout.tie(nullptr);
//    freopen("input.txt","r",stdin);
//    freopen("output.txt","w",stdout);

    int t = 1;
//    cin >> t;

    while(t--)
        solve_case();

    return 0;
}
