Problem:
Problem I:
How to Create a Good Game
A video game company called ICPC (International Company for Playing and Competing) is now developing a new arcade game. The new game features a lot of branches. This makes the game enjoyable for everyone, since players can choose their routes in the game depending on their skills. Rookie players can choose an easy route to enjoy the game, and talented players can choose their favorite routes to get high scores.
In the game, there are many checkpoints connected by paths. Each path consists of several stages, and completing stages on a path leads players to the next checkpoint. The game ends when players reach a particular checkpoint. At some checkpoints, players can choose which way to go, so routes diverge at that time. Sometimes different routes join together at a checkpoint. The paths between checkpoints are directed, and there is no loop (otherwise, players can play the game forever). In other words, the structure of the game can be viewed as a DAG (directed acyclic graph), when considering paths between checkpoints as directed edges.
Recently, the development team completed the beta version of the game and received feedbacks from other teams. They were quite positive overall, but there are some comments that should be taken into consideration. Some testers pointed out that some routes were very short compared to the longest ones. Indeed, in the beta version, the number of stages in one play can vary drastically depending on the routes. Game designers complained many brilliant ideas of theirs were unused in the beta version because of the tight development schedule. They wanted to have more stages included in the final product.
However, it’s not easy to add more stages. this is an arcade game – if the playing time was too long, it would bring down the income of the game and owners of arcades would complain. So, the longest route of the final product can’t be longer than that of the beta version. Moreover, the producer of the game didn’t want to change the structure of paths (i.e., how the checkpoints connect to each other), since it would require rewriting the scenario, recording voices, creating new cutscenes, etc.
Considering all together, the producer decided to add as many new stages as possible, while keeping the maximum possible number of stages in one play and the structure of paths unchanged. How many new stages can be added to the game?
Input
N M
x
1
y
1
s
1
.
.
.
x
M
y
M
s
M
The first line of the input contains two positive integers
N
and
M
(2 ≤
N
≤ 100, 1 ≤
M
≤ 1000).
N
indicates the number of checkpoints, including the opening and ending of the game.
M
indicates the number of paths between checkpoints.
The following
M
lines describe the structure of paths in the beta version of the game. The
i
-th line contains three integers
x
i
,
y
i
and
s
i
(0 ≤
x
i
<
y
i
≤
N
- 1, 1 ≤
s
i
≤ 1000), which describe that there is a path from checkpoint
x
i
to
y
i
consists of si stages. As for indices of the check
...(truncated)

Submitted solutions:

code_snippet: #include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define add(a,b,c) (e[i]=b,pre[i]=last[a],last[a]=i,w[i]=c)
#define prec 1e-6
#define inf 1e9
using namespace std;
struct edge
{    int u,v,w;
   edge(int u=0,int v=0,int w=0):u(u),v(v),w(w) {}
};
struct simplex
{    double v;
   double a[1205][1205];
   double b[1205];
   double c[1205];
   int basic[1205];
   int nbasic[105];
   void pivot(int l,int e);
   double opt();
   void output();
};
int fcmp(double x)
{    if (fabs(x)<prec)
       return 0;
   return x>0?1:-1;
}
edge ed[1005];
int last[1005];
int pre[2005];
int deg[105];
int e[2005];
int w[2005];
int f[105];
int n,m;
simplex lp;
void simplex::output()
{    int i,j;
   for (i=1;i<=m;++i)
   {    printf("x[%d]=%.2f-",basic[i],b[basic[i]]);
       for (j=1;j<=n;++j)
           printf("%c%.2fx[%d]",j==1?'(':'+',a[basic[i]][nbasic[j]],nbasic[j]);
       printf(")\n");
   }
   printf("maximize ");
   printf("%.2f",v);
   for (i=1;i<=n;++i)
       printf("+%.2fx[%d]",c[nbasic[i]],nbasic[i]);
   printf("\n\n");
}
void simplex::pivot(int l,int e)
{    static double ta[1205][1205];
   static double tb[1205];
   static double tc[1205];
   int i,j;
   memset(ta,0,sizeof(ta));
   memset(tb,0,sizeof(tb));
   memset(tc,0,sizeof(tc));
   tb[e]=b[l]/a[l][e];
   ta[e][l]=1.0/a[l][e];
   for (i=1;i<=n;++i)
       if (nbasic[i]!=e)
           ta[e][nbasic[i]]=a[l][nbasic[i]]/a[l][e];
   for (i=1;i<=m;++i)
   {    tb[basic[i]]=b[basic[i]]-a[basic[i]][e]*tb[e];
       ta[basic[i]][l]=-a[basic[i]][e]*ta[e][l];
       for (j=1;j<=n;++j)
           if (nbasic[j]!=e)
               ta[basic[i]][nbasic[j]]=a[basic[i]][nbasic[j]]-a[basic[i]][e]*ta[e][nbasic[j]];
   }
   v=v+tb[e]*c[e];
   tc[l]=-ta[e][l]*c[e];
   for (i=1;i<=n;++i)
       if (nbasic[i]!=e)
           tc[nbasic[i]]=c[nbasic[i]]-c[e]*ta[e][nbasic[i]];
   for (i=1;i<=n;++i)
       if (nbasic[i]==e)
           nbasic[i]=l;
   for (i=1;i<=m;++i)
       if (basic[i]==l)
           basic[i]=e;
   for (i=1;i<=m;++i)
   {    for (j=1;j<=n;++j)
           a[basic[i]][nbasic[j]]=ta[basic[i]][nbasic[j]];
       b[basic[i]]=tb[basic[i]];
   }
   for (i=1;i<=n;++i)
       c[nbasic[i]]=tc[nbasic[i]];
}
double simplex::opt()
{    double delta;
   int i,l,e;
   while (1)
   {    e=n+m+2;
       for (i=1;i<=n;++i)
           if (fcmp(c[nbasic[i]])>0&&nbasic[i]<e)
               e=nbasic[i];
       if (e==n+m+2)
           return v;
       delta=-1;
       l=n+m+2;
       for (i=1;i<=m;++i)
           if (fcmp(a[basic[i]][e])>0)
           {    double t=b[basic[i]]/a[basic[i]][e];
               if (l==n+m+2||fcmp(t-delta)<0||(fcmp(t-delta)==0&&basic[i]<l))
               {    delta=t;
                   l=basic[i];
               }
           }
       if (l==n+m+2)
           return inf;
       else pivot(l,e);
   }
}
int longest_path()
{    int q[105];
   int i,h,t;
   q[h=t=1]=1;
   while (h<=t)
   {    for (i=last[q[h]];i!=0;i=pre[i])
       {    f[e[i]]=max(f[e[i]],f[q[h]]+w[i]);
           --deg[e[i]];
           if (deg[e[i]]==0)
               q[++t]=e[i];
       }
       ++h;
   }
   return f[n];
}
void buildlp()
{    int i,j;
   for (i=1;i<=n;++i)
       lp.nbasic[i]=i;
   for (i=1;i<=m;++i)
   {    ++lp.c[ed[i].v];
       --lp.c[ed[i].u];
       lp.v+=f[ed[i].v]-f[ed[i].u]-ed[i].w;
   }
   for (i=1;i<=m;++i)
   {    lp.a[n+i][ed[i].v]=-1;
       lp.a[n+i][ed[i].u]=1;
       lp.b[n+i]=f[ed[i].v]-f[ed[i].u]-ed[i].w;
       lp.basic[i]=n+i;
   }
   for (i=1;i<n;++i)
   {    lp.a[n+m+i][i]=-1;
       lp.basic[m+i]=n+m+i;
   }
   lp.a[n+m+n][n]=1;
   lp.basic[m+n]=n+m+n;
   m+=n;
}
int main()
{    int i,a,b,c;
   scanf("%d%d",&n,&m);
   for (i=1;i<=m;++i)
   {    scanf("%d%d%d",&a,&b,&c);
       ++a,++b;
       ++deg[b];
       ed[i]=edge(a,b,c);
       add(a,b,c);
   }
   longest_path();
   buildlp();
   printf("%d\n",(int)lp.opt());
   fclose(stdin);
   fclose(stdout);
   return 0;
}
//分析：http://blog.sina.com.cn/s/blog_4a0c4e5d0101glxu.html
accuracy: 1
time_ms: 50
memory_kb: 25056
final_rank: 20

code_snippet: #include <cstdio>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<long, long> P;
#define V 10010
long INF2 = 400000, INF = 1e9;

// https://lepton.hatenablog.jp/entry/2015/08/07/185540
// https://yang33-kassa.jp/aoj/aoj2230/
// https://sigma425.hatenablog.com/entry/2015/07/12/235941

struct edge {
	long to, cap, cost, rev;

};
typedef vector<edge> vertex;
typedef vector<vertex> graph;
long dist[V];
long h[V];
long prevv[V], preve[V];

vertex g[V];

void add_edge(int from, int to, int cap, int cost) {
	//cout<<from<<" "<<to<<" "<<cap<<" "<<cost<<endl;
	g[from].push_back((edge) { to, cap, cost, (int)g[to].size() });
	g[to].push_back((edge) { from, 0, -cost, (int)g[from].size() - 1 });
}

long min_cost_flow(int s, int t, long f) {
	long res = 0;
	fill(h, h + V, 0);
	for (int i = 0; i < V; i++) {
		for (int j = 0; j < g[i].size(); j++) {
			edge& e = g[i][j];
			if (e.cap == 0) continue;
			int u = e.to;
			h[u] = min(h[u], h[i] + e.cost);
		}
	}
	while (f > 0) {
		priority_queue<P, vector<P>, greater<P> > q;
		fill(dist, dist + V, INF);
		dist[s] = 0;
		q.push(P(0, s));
		while (!q.empty()) {
			P p = q.top(); q.pop();
			int v = p.second;
			if (dist[v] < p.first) continue;
			for (int i = 0; i < g[v].size(); i++) {
				edge& e = g[v][i];
				if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
					dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
					prevv[e.to] = v;
					preve[e.to] = i;
					q.push(P(dist[e.to], e.to));
				}
			}
		}
		for (int v = 0; v < V; v++)h[v] += dist[v];

		long d = f;
		for (int v = t; v != s; v = prevv[v]) {
			d = min(d, g[prevv[v]][preve[v]].cap);
		}
		f -= d;
		res += d * h[t];
		for (int v = t; v != s; v = prevv[v]) {
			edge& e = g[prevv[v]][preve[v]];
			e.cap -= d;
			g[v][e.rev].cap += d;
		}
	}
	return res;
}

#define N 1100
long f[N][N];
long d[N];

int main() {
	int n, m;
	scanf("%d%d", &n, &m);
	int s = 0, t = n - 1, t2 = n;
	for (int i = 0; i < n; i++) fill(f[i], f[i] + N, INF);
	for (int i = 0; i < m; i++) {
		int x, y, c;
		scanf("%d%d%d", &x, &y, &c);
		c *= -1;
		f[x][y] = c;
		add_edge(x, y, INF, c);
		add_edge(x, y, 1, c - INF2);
	}
	for (int k = 0; k < n; k++)
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
				f[i][j] = min(f[i][j], f[i][k] + f[k][j]);
	add_edge(t, t2, INF, -f[0][n - 1]);
	long res = min_cost_flow(s, t2, INF2);
	res += INF2 * m;
	printf("%ld\n", res);
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 4088
final_rank: 10

code_snippet: #include <cstdio>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<long, long> P;
#define V 10010
long INF2 = 400000, INF = 1e9;

// https://lepton.hatenablog.jp/entry/2015/08/07/185540

struct edge {
	long to, cap, cost, rev;

};
typedef vector<edge> vertex;
typedef vector<vertex> graph;
long dist[V];
long h[V];
long prevv[V], preve[V];

vertex g[V];

void add_edge(int from, int to, int cap, int cost) {
	//cout<<from<<" "<<to<<" "<<cap<<" "<<cost<<endl;
	g[from].push_back((edge) { to, cap, cost, (int)g[to].size() });
	g[to].push_back((edge) { from, 0, -cost, (int)g[from].size() - 1 });
}

long min_cost_flow(int s, int t, long f) {
	long res = 0;
	fill(h, h + V, 0);
	for (int i = 0; i < V; i++) {
		for (int j = 0; j < g[i].size(); j++) {
			edge& e = g[i][j];
			if (e.cap == 0) continue;
			int u = e.to;
			h[u] = min(h[u], h[i] + e.cost);
		}
	}
	while (f > 0) {
		priority_queue<P, vector<P>, greater<P> > q;
		fill(dist, dist + V, INF);
		dist[s] = 0;
		q.push(P(0, s));
		while (!q.empty()) {
			P p = q.top(); q.pop();
			int v = p.second;
			if (dist[v] < p.first) continue;
			for (int i = 0; i < g[v].size(); i++) {
				edge& e = g[v][i];
				if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
					dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
					prevv[e.to] = v;
					preve[e.to] = i;
					q.push(P(dist[e.to], e.to));
				}
			}
		}
		for (int v = 0; v < V; v++)h[v] += dist[v];

		long d = f;
		for (int v = t; v != s; v = prevv[v]) {
			d = min(d, g[prevv[v]][preve[v]].cap);
		}
		f -= d;
		res += d * h[t];
		for (int v = t; v != s; v = prevv[v]) {
			edge& e = g[prevv[v]][preve[v]];
			e.cap -= d;
			g[v][e.rev].cap += d;
		}
	}
	return res;
}

#define N 1100
long f[N][N];
long d[N];

int main() {
	int n, m;
	scanf("%d%d", &n, &m);
	int s = 0, t = n - 1, t2 = n;
	for (int i = 0; i < n; i++) fill(f[i], f[i] + N, INF);
	for (int i = 0; i < m; i++) {
		int x, y, c;
		scanf("%d%d%d", &x, &y, &c);
		c *= -1;
		f[x][y] = c;
		add_edge(x, y, INF, c);
		add_edge(x, y, 1, c - INF2);
	}
	for (int k = 0; k < n; k++)
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
				f[i][j] = min(f[i][j], f[i][k] + f[k][j]);
	add_edge(t, t2, INF, -f[0][n - 1]);
	long res = min_cost_flow(s, t2, INF2);
	res += INF2 * m;
	printf("%ld\n", res);
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 4088
final_rank: 10

code_snippet: //#define _GLIBCXX_DEBUG

#include<bits/stdc++.h>
using namespace std;

#define endl '\n'
#define lfs cout<<fixed<<setprecision(10)
#define ALL(a)  (a).begin(),(a).end()
#define ALLR(a)  (a).rbegin(),(a).rend()
#define UNIQUE(a) (a).erase(unique((a).begin(),(a).end()),(a).end())
#define spa << " " <<
#define fi first
#define se second
#define MP make_pair
#define MT make_tuple
#define PB push_back
#define EB emplace_back
#define rep(i,n,m) for(ll i = (n); i < (ll)(m); i++)
#define rrep(i,n,m) for(ll i = (ll)(m) - 1; i >= (ll)(n); i--)
using ll = long long;
using ld = long double;
const ll MOD1 = 1e9+7;
const ll MOD9 = 998244353;
const ll INF = 1e18;
using P = pair<ll, ll>;
template<typename T> using PQ = priority_queue<T>;
template<typename T> using QP = priority_queue<T,vector<T>,greater<T>>;
template<typename T1, typename T2>bool chmin(T1 &a,T2 b){if(a>b){a=b;return true;}else return false;}
template<typename T1, typename T2>bool chmax(T1 &a,T2 b){if(a<b){a=b;return true;}else return false;}
ll median(ll a,ll b, ll c){return a+b+c-max({a,b,c})-min({a,b,c});}
void ans1(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}
void ans2(bool x){if(x) cout<<"YES"<<endl;else cout<<"NO"<<endl;}
void ans3(bool x){if(x) cout<<"Yay!"<<endl;else cout<<":("<<endl;}
template<typename T1,typename T2>void ans(bool x,T1 y,T2 z){if(x)cout<<y<<endl;else cout<<z<<endl;}  
template<typename T1,typename T2,typename T3>void anss(T1 x,T2 y,T3 z){ans(x!=y,x,z);};  
template<typename T>void debug(const T &v,ll h,ll w,string sv=" "){for(ll i=0;i<h;i++){cout<<v[i][0];for(ll j=1;j<w;j++)cout<<sv<<v[i][j];cout<<endl;}};
template<typename T>void debug(const T &v,ll n,string sv=" "){if(n!=0)cout<<v[0];for(ll i=1;i<n;i++)cout<<sv<<v[i];cout<<endl;};
template<typename T>void debug(const vector<T>&v){debug(v,v.size());}
template<typename T>void debug(const vector<vector<T>>&v){for(auto &vv:v)debug(vv,vv.size());}
template<typename T>void debug(stack<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(queue<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(deque<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop_front();}cout<<endl;}
template<typename T>void debug(PQ<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(QP<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(const set<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T>void debug(const multiset<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T,size_t size>void debug(const array<T, size> &a){for(auto z:a)cout<<z<<" ";cout<<endl;}
template<typename T,typename V>void debug(const map<T,V>&v){for(auto z:v)cout<<"["<<z.first<<"]="<<z.second<<",";cout<<endl;}
template<typename T>vector<vector<T>>vec(ll x, ll y, T w){vector<vector<T>>v(x,vector<T>(y,w));return v;}
ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;}
vector<ll>dx={1,-1,0,0,1,1,-1,-1};vector<ll>dy={0,0,1,-1,1,-1,1,-1};
template<typename T>vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<typename... Ts>auto make_v(size_t a,Ts... ts){return vector<decltype(make_v(ts...))>(a,make_v(ts...));}
template<typename T1, typename T2>ostream &operator<<(ostream &os, const pair<T1, T2>&p){return os << p.first << " " << p.second;}
template<typename T>ostream &operator<<(ostream &os, const vector<T> &v){for(auto &z:v)os << z << " ";cout<<"|"; return os;}
template<typename T>void rearrange(vector<int>&ord, vector<T>&v){
  auto tmp = v;
  for(int i=0;i<tmp.size();i++)v[i] = tmp[ord[i]];
}
template<typename Head, typename... Tail>void rearrange(vector<int>&ord,Head&& head, Tail&&... tail){
  rearrange(ord, head);
  rearrange(ord, tail...);
}
template<typename T> vector<int> ascend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]<v[j];});
  return ord;
}
template<typename T> vector<int> descend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]>v[j];});
  return ord;
}
ll FLOOR(ll n,ll div){assert(div>0);return n>=0?n/div:(n-div+1)/div;}
ll CEIL(ll n,ll div){assert(div>0);return n>=0?(n+div-1)/div:n/div;}
ll digitsum(ll n){ll ret=0;while(n){ret+=n%10;n/=10;}return ret;}
ll modulo(ll n,ll d){return (n%d+d)%d;};
template<typename T>T min(const vector<T>&v){return *min_element(v.begin(),v.end());}
template<typename T>T max(const vector<T>&v){return *max_element(v.begin(),v.end());}
template<typename T>T acc(const vector<T>&v){return accumulate(v.begin(),v.end(),T(0));};
template<typename T>T reverse(const T &v){return T(v.rbegin(),v.rend());};
//mt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
int popcount(ll x){return __builtin_popcountll(x);};
int poplow(ll x){return __builtin_ctzll(x);};
int pophigh(ll x){return 63 - __builtin_clzll(x);};
template<typename T>T poll(queue<T> &q){auto ret=q.front();q.pop();return ret;};
template<typename T>T poll(priority_queue<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(QP<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(stack<T> &s){auto ret=s.top();s.pop();return ret;};
ll MULT(ll x,ll y){if(LLONG_MAX/x<=y)return LLONG_MAX;return x*y;}
ll POW2(ll x, ll k){ll ret=1,mul=x;while(k){if(mul==LLONG_MAX)return LLONG_MAX;if(k&1)ret=MULT(ret,mul);mul=MULT(mul,mul);k>>=1;}return ret;}
ll POW(ll x, ll k){ll ret=1;for(int i=0;i<k;i++){if(LLONG_MAX/x<=ret)return LLONG_MAX;ret*=x;}return ret;}
template< typename T = int >
struct edge {
  int to;
  T cost;
  int id;
  edge():id(-1){};
  edge(int to, T cost = 1, int id = -1):to(to), cost(cost), id(id){}
  operator int() const { return to; }
};

template<typename T>
using Graph = vector<vector<edge<T>>>;
template<typename T>
Graph<T>revgraph(const Graph<T> &g){
  Graph<T>ret(g.size());
  for(int i=0;i<g.size();i++){
    for(auto e:g[i]){
      int to = e.to;
      e.to = i;
      ret[to].push_back(e);
    }
  }
  return ret;
}
template<typename T>
Graph<T> readGraph(int n,int m,int indexed=1,bool directed=false,bool weighted=false){
  Graph<T> ret(n);
  for(int es = 0; es < m; es++){
    int u,v;
    T w=1;
    cin>>u>>v;u-=indexed,v-=indexed;
    if(weighted)cin>>w;
    ret[u].emplace_back(v,w,es);
    if(!directed)ret[v].emplace_back(u,w,es);
  }
  return ret;
}
template<typename T>
Graph<T> readParent(int n,int indexed=1,bool directed=true){
  Graph<T>ret(n);
  for(int i=1;i<n;i++){
    int p;cin>>p;
    p-=indexed;
    ret[p].emplace_back(i);
    if(!directed)ret[i].emplace_back(p);
  }
  return ret;
}
//BEGIN CUT HERE
// O(m^2 \log m \log U)
// U: maximum capacity
enum Objective{
  MINIMIZE = +1,
  MAXIMIZE = -1,
};
template<typename Flow, typename Cost,
         Objective objective = Objective::MINIMIZE>
struct MinCostFlow{
  template<typename T> inline void chmin(T &x,T y){x=min(x,y);}

  struct Edge{
    int src,dst;
    Flow flow,cap;
    Cost cost;
    int rev;
    Edge(int src,int dst,Flow cap,Cost cost,int rev):
      src(src),dst(dst),flow(0),cap(cap),cost(cost),rev(rev){}
    Flow residual_cap()const{return cap-flow;}
  };

  struct EdgePtr{
    int v,e;
    EdgePtr(int v,int e):v(v),e(e){}
  };

  int n;
  vector<vector<Edge>> G;
  vector<Flow> b;
  vector<Cost> p;

  MinCostFlow(int n):n(n),G(n),b(n,0){}

  EdgePtr add_edge(int src,int dst,Flow lower,Flow upper,Cost cost){
    int e=G[src].size();
    int r=(src==dst?e+1:G[dst].size());
    assert(lower<=upper);
    G[src].emplace_back(src,dst,+upper,+cost*objective,r);
    G[dst].emplace_back(dst,src,-lower,-cost*objective,e);
    return EdgePtr(src,e);
  }

  const Edge &get_edge(EdgePtr ep)const{return G[ep.v][ep.e];}

  void push(Edge &e,Flow amount){
    e.flow+=amount;
    G[e.dst][e.rev].flow-=amount;
  }

  void add_supply(int v,Flow amount){b[v]+=amount;}
  void add_demand(int v,Flow amount){b[v]-=amount;}

  Cost residual_cost(const Edge &e){
    return e.cost+p[e.src]-p[e.dst];
  }

  vector<int> excess_vs,deficit_vs;
  void saturate_negative(const Flow delta){
    for(auto &es:G){
      for(auto &e:es){
        Flow cap=e.residual_cap();
        cap-=cap%delta;
        if(cap<0 or residual_cost(e)<0){
          push(e,cap);
          b[e.src]-=cap;
          b[e.dst]+=cap;
        }
      }
    }

    excess_vs.clear();
    deficit_vs.clear();
    for(int v=0;v<n;v++){
      if(b[v]>0) excess_vs.emplace_back(v);
      if(b[v]<0) deficit_vs.emplace_back(v);
    }
  }

  const Cost unreachable = std::numeric_limits<Cost>::max();
  Cost farthest;
  vector<Cost> dist;
  vector<Edge*> parent;

  struct P{
    Cost first;
    int second;
    P(Cost first,int second):first(first),second(second){}
    bool operator<(const P o)const{return first>o.first;}
  };

  priority_queue<P> pq;

  template<typename Predicate>
  void eliminate(vector<int> &vs,Predicate predicate){
    vs.erase(remove_if(begin(vs),end(vs),predicate),end(vs));
  }

  bool dual(const Flow delta){
    eliminate(excess_vs, [&](int v){return b[v]<+delta;});
    eliminate(deficit_vs,[&](int v){return b[v]>-delta;});

    dist.assign(n,unreachable);
    for(int v:excess_vs) pq.emplace(dist[v]=0,v);

    parent.assign(n,nullptr);
    auto emplace=[&](Edge& e){
      if(e.residual_cap()<delta) return;
      Cost nxt=dist[e.src]+residual_cost(e);
      if(nxt>=dist[e.dst]) return;
      pq.emplace(dist[e.dst]=nxt,e.dst);
      parent[e.dst]=&e;
    };

    farthest=0;
    int deficit_count=0;
    while(!pq.empty()){
      Cost d=pq.top().first;
      int v=pq.top().second;
      pq.pop();
      if(dist[v]<d) continue;
      farthest=d;

      if(b[v]<=-delta) deficit_count++;
      if(deficit_count>=(int)deficit_vs.size()) break;

      for(auto &e:G[v]) emplace(e);
    }
    pq=decltype(pq)();

    for(int v=0;v<n;v++)
      p[v]+=min(dist[v],farthest);

    return deficit_count>0;
  }

  void primal(const Flow delta){
    for(int t:deficit_vs){
      if(dist[t]>farthest) continue;
      Flow f=-b[t];
      int v;
      for(v=t;parent[v];v=parent[v]->src)
        chmin(f,parent[v]->residual_cap());
      chmin(f,b[v]);

      f-=f%delta;
      if(f<=0) continue;

      for(v=t;parent[v];){
        auto &e=*parent[v];
        push(e,f);
        int u=parent[v]->src;
        if(e.residual_cap()<=0) parent[v]=nullptr;
        v=u;
      }
      b[t]+=f;
      b[v]-=f;
    }
  }

  template<Flow SCALING_FACTOR=2>
  bool build(){
    p.resize(n);
    Flow max_flow=1;
    for(auto t:b) max_flow=max({max_flow,t,-t});
    for(auto &es:G)
      for(auto &e:es)
        max_flow=max({max_flow,e.residual_cap(),-e.residual_cap()});

    Flow delta=1;
    while(delta<max_flow) delta*=SCALING_FACTOR;
    for(;delta;delta/=SCALING_FACTOR){
      saturate_negative(delta);
      while(dual(delta)) primal(delta);
    }

    return excess_vs.empty() and deficit_vs.empty();
  }

  template<typename T=Cost>
  T get_cost(){
    T res=0;
    for(auto &es:G)
      for(auto &e:es)
        res+=T(e.flow)*T(e.cost)/T(objective);
    return res/T(2);
  }
  template<typename T=Cost> T get_gain(){return get_cost();}

  vector<Cost> get_potential(){
    fill(p.begin(),p.end(),0);
    for(int i=0;i<n;i++)
      for(auto &es:G)
        for(auto &e:es)
          if(e.residual_cap()>0)
            chmin(p[e.dst],p[e.src]+e.cost);
    return p;
  }
};

template<typename Flow, typename Cost>
using MaxGainFlow = MinCostFlow<Flow, Cost, Objective::MAXIMIZE>;
//END CUT HERE
int main(){
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  ll res=0,buf=0;
  bool judge = true;
	ll n,m;cin>>n>>m;
	auto g=readGraph<ll>(n,m,0,true,true);
	vector<ll>dp(n);
	MinCostFlow<ll,ll>mcf(n);
	ll inf=1e9;
	rep(i,0,n){
		for(auto e:g[i]){
			chmax(dp[e.to],dp[i]+e.cost);
			mcf.add_edge(e.to,i,1,inf,-e.cost);
		}
	}
	mcf.add_edge(0,n-1,0,inf,dp[n-1]);
	assert(mcf.build());
	cout<<mcf.get_cost()<<endl;
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3576
final_rank: 3

code_snippet: #pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<cassert>
#include<complex>
#include<numeric>
#include<array>
#include<chrono>
using namespace std;

//#define int long long
typedef long long ll;

typedef unsigned long long ul;
typedef unsigned int ui;
constexpr ll mod = 1000000007;
const ll INF = mod * mod;
typedef pair<int, int>P;

#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
#define all(v) (v).begin(),(v).end()
typedef pair<ll, ll> LP;
typedef double ld;
typedef pair<ld, ld> LDP;
const ld eps = 1e-4;
const ld pi = acosl(-1.0);

template<typename T>
void chmin(T& a, T b) {
	a = min(a, b);
}
template<typename T>
void chmax(T& a, T b) {
	a = max(a, b);
}
template<typename T>
void cinarray(vector<T>& v) {
	rep(i, v.size())cin >> v[i];
}
template<typename T>
void coutarray(vector<T>& v) {
	rep(i, v.size()) {
		if (i > 0)cout << " "; cout << v[i];
	}
	cout << "\n";
}
ll mod_pow(ll x, ll n, ll m = mod) {
	if (n < 0) {
		ll res = mod_pow(x, -n, m);
		return mod_pow(res, m - 2, m);
	}
	if (abs(x) >= m)x %= m;
	if (x < 0)x += m;
	if (x == 0)return 0;
	ll res = 1;
	while (n) {
		if (n & 1)res = res * x % m;
		x = x * x % m; n >>= 1;
	}
	return res;
}
struct modint {
	int n;
	modint() :n(0) { ; }
	modint(ll m) {
		if (m < 0 || mod <= m) {
			m %= mod; if (m < 0)m += mod;
		}
		n = m;
	}
	operator int() { return n; }
};
bool operator==(modint a, modint b) { return a.n == b.n; }
modint operator+=(modint& a, modint b) { a.n += b.n; if (a.n >= mod)a.n -= mod; return a; }
modint operator-=(modint& a, modint b) { a.n -= b.n; if (a.n < 0)a.n += mod; return a; }
modint operator*=(modint& a, modint b) { a.n = ((ll)a.n * b.n) % mod; return a; }
modint operator+(modint a, modint b) { return a += b; }
modint operator-(modint a, modint b) { return a -= b; }
modint operator*(modint a, modint b) { return a *= b; }
modint operator^(modint a, ll n) {
	if (n == 0)return modint(1);
	modint res = (a * a) ^ (n / 2);
	if (n % 2)res = res * a;
	return res;
}

ll inv(ll a, ll p) {
	return (a == 1 ? 1 : (1 - p * inv(p % a, a)) / a + p);
}
modint operator/(modint a, modint b) { return a * modint(inv(b, mod)); }
modint operator/=(modint& a, modint b) { a = a / b; return a; }
const int max_n = 1 << 20;
modint fact[max_n], factinv[max_n];
void init_f() {
	fact[0] = modint(1);
	for (int i = 0; i < max_n - 1; i++) {
		fact[i + 1] = fact[i] * modint(i + 1);
	}
	factinv[max_n - 1] = modint(1) / fact[max_n - 1];
	for (int i = max_n - 2; i >= 0; i--) {
		factinv[i] = factinv[i + 1] * modint(i + 1);
	}
}
modint comb(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[b] * factinv[a - b];
}
modint combP(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[a - b];
}

ll gcd(ll a, ll b) {
	a = abs(a); b = abs(b);
	if (a < b)swap(a, b);
	while (b) {
		ll r = a % b; a = b; b = r;
	}
	return a;
}

int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };

/*template<typename T>
struct mcf {
private:
	struct edge {
		int to, cap; T cost; int rev;
	};
	vector<vector<edge>> G;
	vector<P> par;
	vector<T> dist;
	T inf = INF/1000;
public:
	mcf(int n) {
		G.resize(n);
		par.resize(n);
		dist.resize(n);
	}
	void add_edge(int from, int to, int cap, T cost) {
		G[from].push_back({ to,cap,cost,(int)G[to].size() });
		G[to].push_back({ from,0,-cost,(int)G[from].size() - 1 });
	}
	pair<T, int> minimum_road(int s, int t) {
		fill(all(par), P{ -1,-1 });
		fill(all(dist), inf);
		dist[s] = 0;
		rep(_, G.size()) {
			rep(id, G.size()) {
				rep(j, G[id].size()) {
					if (G[id][j].cap > 0) {
						int to = G[id][j].to;
						T nd = p.first + G[id][j].cost;
						if (nd < dist[to]) {
							dist[to] = nd;
							par[to] = { id,j };
						}
					}
				}
			}
		}
		int cur = t;
		int f = mod;
		while (cur != s) {
			int p = par[cur].first, j = par[cur].second;
			if (p < 0)return { -1,-1 };
			f = min(f, G[p][j].cap);
			cur = p;
		}
		cur = t;
		while (cur != s) {
			int p = par[cur].first, j = par[cur].second;
			if (p < 0)return { -1,-1 };
			G[p][j].cap -= f;
			if (G[p][j].rev >= 0) {
				G[cur][G[p][j].rev].cap += f;
			}
			cur = p;
		}
		return { dist[t],f };
	}
	T minimum_cost_flow(int s, int t, int k) {
		T ret = 0;
		rep(i, k) {
			pair<T, int> z = minimum_road(s, t);
			if (z.first < 0)return -1;
			if (k - i <= z.second) {
				ret += z.first * (k - i); break;
			}
			i += z.second - 1;
			ret += z.first * z.second;
		}
		return ret;
	}
};*/

template<typename TF, typename TC>
struct PrimalDual {
	struct edge {
		int to;
		TF cap;
		TC cost;
		int rev;
		edge() {}
		edge(int to, TF cap, TC cost, int rev) :
			to(to), cap(cap), cost(cost), rev(rev) {}
	};

	vector<vector<edge>> G;
	vector<TC> h, dist;
	vector<int> prevv, preve;

	PrimalDual() {}
	PrimalDual(int n) :G(n), h(n), dist(n), prevv(n), preve(n) {}

	void add_edge(int u, int v, TF cap, TC cost) {
		G[u].emplace_back(v, cap, cost, G[v].size());
		G[v].emplace_back(u, 0, -cost, G[u].size() - 1);
	}

	void dijkstra(int s) {
		struct P {
			TC first;
			int second;
			P(TC first, int second) :first(first), second(second) {}
			bool operator<(const P& a) const { return a.first < first; }
		};
		priority_queue<P> que;
		fill(dist.begin(), dist.end(), INF);

		dist[s] = 0;
		que.emplace(dist[s], s);
		while (!que.empty()) {
			P p = que.top(); que.pop();
			int v = p.second;
			if (dist[v] < p.first) continue;
			for (int i = 0; i < (int)G[v].size(); i++) {
				edge& e = G[v][i];
				if (e.cap == 0) continue;
				if (dist[v] + e.cost + h[v] - h[e.to] < dist[e.to]) {
					dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
					prevv[e.to] = v;
					preve[e.to] = i;
					que.emplace(dist[e.to], e.to);
				}
			}
		}
	}

	TC flow(int s, int t, TF f, int& ok) {
		TC res = 0;
		fill(h.begin(), h.end(), 0);
		while (f > 0) {
			dijkstra(s);
			if (dist[t] == INF) {
				ok = 0;
				return res;
			}

			for (int v = 0; v < (int)h.size(); v++)
				if (dist[v] < INF) h[v] = h[v] + dist[v];

			TF d = f;
			for (int v = t; v != s; v = prevv[v])
				d = min(d, G[prevv[v]][preve[v]].cap);

			f -= d;
			res = res + h[t] * d;
			for (int v = t; v != s; v = prevv[v]) {
				edge& e = G[prevv[v]][preve[v]];
				e.cap -= d;
				G[v][e.rev].cap += d;
			}
		}
		ok = 1;
		return res;
	}
};

template<typename T>
struct mcf {
private:
	struct edge {
		int to, cap; T cost; int rev;
	};
	vector<vector<edge>> G;
	vector<P> par;
	vector<T> dist;
	T inf = INF / 100000;
public:
	mcf(int n) {
		G.resize(n);
		par.resize(n);
		dist.resize(n);
	}
	void add_edge(int from, int to, int cap, T cost) {
		G[from].push_back({ to,cap,cost,(int)G[to].size() });
		G[to].push_back({ from,0,-cost,(int)G[from].size() - 1 });
	}
	pair<T, int> minimum_road(int s, int t) {
		fill(all(par), P{ -1,-1 });
		fill(all(dist), inf);
		dist[s] = 0;
		priority_queue<pair<T, int>, vector<pair<T, int>>, greater<pair<T, int>>> q;
		q.push({ 0,s });
		while (!q.empty()) {
			pair<T, int> p = q.top(); q.pop();
			int id = p.second;
			if (id == t)continue;
			if (p.first > dist[id])continue;
			rep(j, G[id].size()) {
				if (G[id][j].cap > 0) {
					int to = G[id][j].to;
					T nd = p.first + G[id][j].cost;
					if (nd < dist[to]) {
						dist[to] = nd;
						par[to] = { id,j };
						q.push({ dist[to],to });
					}
				}
			}
		}
		int cur = t;
		int f = mod;
		while (cur != s) {
			int p = par[cur].first, j = par[cur].second;
			if (p < 0)return { -1,-1 };
			f = min(f, G[p][j].cap);
			cur = p;
		}
		cur = t;
		while (cur != s) {
			int p = par[cur].first, j = par[cur].second;
			if (p < 0)return { -1,-1 };
			G[p][j].cap -= f;
			if (G[p][j].rev >= 0) {
				G[cur][G[p][j].rev].cap += f;
			}
			cur = p;
		}
		return { dist[t],f };
	}
	T minimum_cost_flow(int s, int t, int k) {
		T ret = 0;
		rep(i, k) {
			pair<T, int> z = minimum_road(s, t);
			if (z.first < 0)return -1;
			if (k - i <= z.second) {
				ret += z.first * (k - i); break;
			}
			i += z.second - 1;
			ret += z.first * z.second;
		}
		return ret;
	}
};
struct edge {
	int to, cost;
};
void solve() {
	int n, m; cin >> n >> m;
	vector<vector<edge>> G(n);
	rep(i, m) {
		int a, b, c; cin >> a >> b >> c;
		G[a].push_back({ b,c });
	}
	vector<int> dp(n);
	rep(i, n) {
		for (edge e : G[i]) {
			chmax(dp[e.to], dp[i] + e.cost);
		}
	}
	int D = dp[n - 1];
	//cout << D << "\n";
	mcf<ll> mc(n + 2);
	//mcf<ll> mc(n + 2);
	int s = n;
	int t = n + 1;
	vector<int> d(n);
	ll ans = 0;
	mc.add_edge(0, n - 1, mod, D);
	//G[0].push_back({ n - 1,D });
	int sum = 0;
	rep(i, n) {
		for (edge e : G[i]) {
			/*ans += e.cost;
			d[i] += -1;
			d[e.to] -= -1;*/

			//mc.add_edge(i, e.to, -1, e.cost);

			//mc.add_edge(e.to,i,1,-e.cost-mod)
			ans += -e.cost - mod/3;
			d[i]++;
			d[e.to]--;
			mc.add_edge(i, e.to, 1, e.cost + mod/3);

			//mc.add_edge(e.to, i, 10000, -e.cost);
			ans += 100000 * (-e.cost);
			d[i] += 100000;
			d[e.to] -=100000;
			mc.add_edge(i,e.to, 100000, e.cost);
		}
	}
	rep(i, n) {
		if (d[i] > 0) {
			sum += d[i];
			mc.add_edge(s, i, d[i], 0);
		}
		else {
			mc.add_edge(i, t, -d[i], 0);
		}
	}
	//cout << -ans << "\n";
	//int ok;
	ans += mc.minimum_cost_flow(s, t, sum);
	ans += mod/3 * m;
	cout << ans<< "\n";
}

signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	//cout << fixed << setprecision(8);
	//init_f();
	//init();
	//while(true)
	//expr();
	//int t; cin >> t; rep(i, t)
	solve();
	return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 11784
final_rank: 17

code_snippet: #include <bits/stdc++.h>

#define eprintf(args...) fprintf(stderr, args)
#define rep(i, n) for (int i = 0; i < (int)(n); ++ i)

struct Edge {
	int v, w, c, r;
};

struct MinCostFlow {
	static const int mxn = 105;
	int n, S, T;
	std::vector <Edge> adj[mxn];
	int dis[mxn], h[mxn];
	int que[mxn], ql, qr;
	bool inque[mxn];
	std::priority_queue <std::pair <int, int> > pq;
	bool vis[mxn];
	int id[mxn];

	void init(int _n, int _S, int _T) {
		n = _n, S = _S, T = _T;
		rep(i, n) adj[i].clear();
	}

	inline void add_edge(int u, int v, int w, int c) {
		adj[u].push_back({v, w, c, (int) adj[v].size()});
		adj[v].push_back({u, 0, -c, (int) adj[u].size() - 1});
	}

	bool spfa() {
		rep(i, n) h[i] = i == S ? 0 : 0x3f3f3f3f;
		ql = qr = 0; que[qr ++] = S;
		rep(i, n) inque[i] = i == S ? 1 : 0;
		while (ql != qr) {
			int u = que[ql ++]; if (ql == mxn) ql = 0;
			inque[u] = false;
			rep(i, adj[u].size()) {
				Edge e = adj[u][i];
				if (e.w && h[e.v] > h[u] + e.c) {
					h[e.v] = h[u] + e.c;
					if (!inque[e.v]) {
						inque[e.v] = true;
						que[qr ++] = e.v; if (qr == mxn) qr = 0;
					}
				}
			}
		}
		rep(i, n) dis[i] = h[i];
		return dis[T] < 1e9;
	}

	bool dij() {
		rep(i, n) h[i] = i == S ? 0 : 0x3f3f3f3f;
		pq.push({-h[S], S});
		while (!pq.empty()) {
			int u = pq.top().second;
			int d = -pq.top().first;
			pq.pop();
			if (d != h[u]) continue;
			rep(i, adj[u].size()) {
				Edge e = adj[u][i];
				if (e.w && h[e.v] > h[u] + e.c + dis[u] - dis[e.v]) {
					h[e.v] = h[u] + e.c + dis[u] - dis[e.v];
					pq.push({-h[e.v], e.v});
				}
			}
		}
		rep(i, n) dis[i] += h[i];
		return dis[T] < 1e9;
	}

	int dfs(int u, int f = 0x3f3f3f3f) {
		if (u == T) return f;
		int flow = 0;
		vis[u] = true;
		for (int &i = id[u]; i < (int) adj[u].size(); ++ i) {
			Edge e = adj[u][i];
			if (e.w && dis[e.v] == dis[u] + e.c && !vis[e.v]) {
				int d = dfs(e.v, std::min(f, e.w));
				if (d) {
					adj[u][i].w -= d;
					adj[e.v][adj[u][i].r].w += d;
					flow += d, f -= d;
					if (f == 0) break;
				}
			}
		}
		vis[u] = false;
		return flow;
	}

	int solve() {
		spfa();
		int ans = 0;
		while (dij()) {
			rep(i, n) vis[i] = false, id[i] = 0;
			ans += dfs(S) * dis[T];
		}
		return ans;
	}
} mcf;

const int mxn = 1005;
const int M = 1000003, inf = 0x3f3f3f3f;
int n, m;
int E[mxn][3];
std::vector <std::pair <int, int> > adj[mxn];

bool vis[mxn];
int rem[mxn];
int dfs(int u) {
	if (u == n - 1) return 0;
	if (vis[u]) return rem[u];
	vis[u] = true;
	rem[u] = -0x3f3f3f3f;
	for (auto pr : adj[u]) {
		int v = pr.first, w = pr.second;
		rem[u] = std::max(rem[u], dfs(v) + w);
	}
	return rem[u];
}

int main() {
	scanf("%d %d", &n, &m);
	rep(i, m) {
		scanf("%d %d %d", &E[i][0], &E[i][1], &E[i][2]);
		adj[E[i][0]].push_back({E[i][1], E[i][2]});
	}
	int L = dfs(0);
	int S = n, T = n + 1, S0 = n + 2;
	mcf.init(n + 3, S, T);
	mcf.add_edge(S, S0, inf, L);
	rep(i, m) {
		int u, v, w;
		u = E[i][0], v = E[i][1], w = E[i][2];
		mcf.add_edge(u, v, 1, -M - w);
		mcf.add_edge(u, v, inf, -w);
	}
	mcf.add_edge(S0, 0, inf, 0);
	mcf.add_edge(n - 1, T, inf, 0);
	printf("%d\n", mcf.solve() + M * m);
	return 0;
}

/*
   max sum a_{u, v}
   forall u, v, d_u - d_v + a_{u, v} <= -w_{u, v}   --> x_{u, v}
   d_T - d_S <= L                                   --> F

   <=>

   min sum -w_{u, v} x_{u, v} + L * F
   forall u, sum v x_{u, v} - sum v x_{v, u} - [u == S] F + [u == T] F >= (==) 0
   forall u, v, x_{u, v} >= 1
*/
accuracy: 1
time_ms: 20
memory_kb: 3748
final_rank: 9

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2005;
struct Graph{
	struct Edge{ int to,nxt,c,k; }edge[N*2];
	int head[N],top;
	Graph(){memset(head,-1,sizeof(head)),top=-1;}
	inline void add(int x,int y,int c,int k){
		edge[++top]=(Edge){y,head[x],c,k};
		head[x]=top;
	}
}G,G1;
inline void add2(int x,int y,int c,int k){
//	printf("(%d %d %d %d)\n",x,y,c,k);
	G.add(x,y,c,k),G.add(y,x,0,-k);
}
namespace FLOW{
	int iter[N],lev[N];
	ll h[N],dis[N];
	bool dij(Graph& G,int s,int t,int n){
		priority_queue<pair<ll,int>,vector<pair<ll,int> >,greater<pair<ll,int> > > q;
		for(int i=0;i<=n;++i) iter[i]=G.head[i],lev[i]=0,dis[i]=1e18;
		dis[t]=0; lev[t]=1; q.push(make_pair(dis[t],t));
		while(!q.empty()){
			int x=q.top().second; ll k=q.top().first; q.pop();
			if(k!=dis[x]) continue;
			for(int j=G.head[x];~j;j=G.edge[j].nxt){
				int y=G.edge[j].to; ll k1=G.edge[j^1].k+h[x]-h[y];
				if(G.edge[j^1].c>0&&dis[x]+k1<dis[y]){
					dis[y]=dis[x]+k1; lev[y]=lev[x]+1;
					q.push(make_pair(dis[y],y));
				}
			}
		}
		return lev[s]>0;
	}
	int dfs(Graph& G,int x,int t,int mx){
		if(x==t) return mx;
		int ret=0;
		for(int& j=iter[x];~j;j=G.edge[j].nxt){
			int y=G.edge[j].to;
			if(G.edge[j].c>0&&lev[y]==lev[x]-1&&G.edge[j].k+h[y]-h[x]==0){
				int d=dfs(G,y,t,min(mx-ret,G.edge[j].c));
				G.edge[j].c-=d; G.edge[j^1].c+=d; ret+=d;
				if(ret==mx) break;
			}
		}
		return ret;
	}
	pair<ll,int> cost_flow2(Graph& G,int s,int t,int n,int mx){
		for(int i=0;i<=n;++i) h[i]=0;
		pair<ll,int> ret(0,0);
		while(mx>ret.second&&dij(G,s,t,n)){
			for(int i=0;i<=n;++i) h[i]+=dis[i];
			int d=dfs(G,s,t,mx-ret.second);
			if(h[s]>=0) break;
			ret.first+=h[s]*d;
			ret.second+=d;
		}
		return ret;
	}
}
int dis[N];
void bfs(Graph& G,int dis[],int s,int t,int n){
	static int rd[N];
	for(int i=1;i<=n;++i) rd[i]=0,dis[i]=0;
	for(int x=1;x<=n;++x)
		for(int j=G.head[x];~j;j=G.edge[j].nxt)
			rd[G.edge[j].to]++;
	queue<int> q; q.push(s);
	while(!q.empty()){
		int x=q.front(); q.pop();
		for(int j=G.head[x];~j;j=G.edge[j].nxt){
			int y=G.edge[j].to;
			dis[y]=max(dis[y],dis[x]+G.edge[j].k);
			--rd[y]; if(rd[y]==0) q.push(y);
		}
	}
}
int e[N];
int main(){
	int n,m; scanf("%d%d",&n,&m);
	ll ans=0;
	for(int i=1;i<=m;++i){
		int x,y,c; scanf("%d%d%d",&x,&y,&c);
		++x; ++y;
		G1.add(x,y,0,c); add2(x,y,1e9,-c); add2(x,y,1,-c-1e9); 
		ans+=(int)1e9;
	}
	bfs(G1,dis,1,n,n);
	add2(n,n+1,1e9,dis[n]);
	pair<ll,int> ret=FLOW::cost_flow2(G,1,n+1,n+1,1e9);
	ans+=ret.first;
	printf("%lld\n",ans);
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3316
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
template<class T>
inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return true;
    }
    return false;
}

template<class T>
inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return true;
    }
    return false;
}

template< typename flow_t, typename cost_t >
struct PrimalDual {
    const cost_t INF;

    struct edge {
        int to;
        flow_t cap;
        cost_t cost;
        int rev;
        bool isrev;
    };
    vector< vector< edge > > graph;
    vector< cost_t > potential, min_cost;
    vector< int > prevv, preve;

    PrimalDual(int V) : graph(V), INF(numeric_limits< cost_t >::max()) {}

    void add_edge(int from, int to, flow_t cap, cost_t cost) {
        graph[from].emplace_back((edge) {to, cap, cost, (int) graph[to].size(), false});
        graph[to].emplace_back((edge) {from, 0, -cost, (int) graph[from].size() - 1, true});
    }

    cost_t min_cost_flow(int s, int t, flow_t f) {
        int V = (int) graph.size();
        cost_t ret = 0;
        using Pi = pair< cost_t, int >;
        priority_queue< Pi, vector< Pi >, greater< Pi > > que;
        potential.assign(V, 0);
        preve.assign(V, -1);
        prevv.assign(V, -1);

        while(f > 0) {
            min_cost.assign(V, INF);
            que.emplace(0, s);
            min_cost[s] = 0;
            while(!que.empty()) {
                Pi p = que.top();
                que.pop();
                if(min_cost[p.second] < p.first) continue;
                for(int i = 0; i < graph[p.second].size(); i++) {
                    edge &e = graph[p.second][i];
                    cost_t nextCost = min_cost[p.second] + e.cost + potential[p.second] - potential[e.to];
                    if(e.cap > 0 && min_cost[e.to] > nextCost) {
                        min_cost[e.to] = nextCost;
                        prevv[e.to] = p.second, preve[e.to] = i;
                        que.emplace(min_cost[e.to], e.to);
                    }
                }
            }
            if(min_cost[t] == INF) return -1;
            for(int v = 0; v < V; v++) potential[v] += min_cost[v];
            flow_t addflow = f;
            for(int v = t; v != s; v = prevv[v]) {
                addflow = min(addflow, graph[prevv[v]][preve[v]].cap);
            }
            f -= addflow;
            ret += addflow * potential[t];
            for(int v = t; v != s; v = prevv[v]) {
                edge &e = graph[prevv[v]][preve[v]];
                e.cap -= addflow;
                graph[v][e.rev].cap += addflow;
            }
       }
       return ret;
    }

    void output() {
        for(int i = 0; i < graph.size(); i++) {
            for(auto &e : graph[i]) {
                if(e.isrev) continue;
                auto &rev_e = graph[e.to][e.rev];
                cout << i << "->" << e.to << " (flow: " << rev_e.cap << "/" << rev_e.cap + e.cap << ")" << endl;
            }
        }
    }
};

ll N, M;
ll degree[305];
vector<l_l> edges[305];
ll dist[305];
ll MAX;
ll f = 0;
ll ans = 0;
const ll INF = 1e9;

int main() {
    cin >> N >> M;
    for(int i = 0; i < M; i++) {
        ll u, v, c;
        cin >> u >> v >> c;
        degree[v]++;
        degree[u]--;
        edges[u].push_back({v, c});
    }
    for(int i = 0; i < N; i++) {
        for(auto tmp : edges[i]) {
            chmax(dist[tmp.first], dist[i] + tmp.second);
        }
    }
    MAX = dist[N-1];
    ll s = N;
    ll t = N + 1;
    PrimalDual<ll, ll> g(t + 1);
    for(int i = 0; i < N; i++) {
        for(auto e : edges[i]) {
            g.add_edge(i, e.first, 1, - INF -e.second);
            g.add_edge(i, e.first, 1e9, -e.second);
        }
    }
    g.add_edge(N - 1, t, 1e9, MAX);
    //cerr << MAX << endl;
    g.add_edge(s, 0, 1e9, 0);
    while(true) {
        auto tmp = g.min_cost_flow(s, t, 1);
        if(tmp == -1) break;
        if(tmp == 0) break;
        ans += tmp;
        //cerr << tmp << endl;
    }
    //g.output();
    //cerr << ans << endl;
    auto tmp = g.min_cost_flow(s, t, f);
    //g.output();
    //cerr << tmp.first << " " << tmp.second << endl;
    //ans += tmp.second;
    ans += tmp;
    /*
    while(true) {
    g.output();
        cerr << "A" << endl;
        auto tmp = g.min_cost_flow(s, t, 1);
        cerr << tmp << endl;
        if(tmp <= 0) break;
        ans += tmp;
    }
    */
    //cerr << tmp << endl;
    ans += INF * M;
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 110
memory_kb: 3676
final_rank: 19

code_snippet: #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2230"

#include<bits/stdc++.h>
using namespace std;

#define call_from_test

#ifndef call_from_test
#include <bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif


#ifndef call_from_test
#include <bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
// O(m^2 \log n \log U)
// U: maximum capacity
enum Objective{
  MINIMIZE = +1,
  MAXIMIZE = -1,
};
template<typename Flow, typename Cost,
         Objective objective = Objective::MINIMIZE>
struct MinCostFlow{
  template<typename T> inline void chmin(T &x,T y){x=min(x,y);}

  struct Edge{
    int src,dst;
    Flow flow,cap;
    Cost cost;
    int rev;
    Edge(int src,int dst,Flow cap,Cost cost,int rev):
      src(src),dst(dst),flow(0),cap(cap),cost(cost),rev(rev){}
    Flow residual_cap()const{return cap-flow;}
  };

  struct EdgePtr{
    int v,e;
    EdgePtr(int v,int e):v(v),e(e){}
  };

  int n;
  vector<vector<Edge>> G;
  vector<Flow> b;
  vector<Cost> p;

  MinCostFlow(int n):n(n),G(n),b(n,0){}

  EdgePtr add_edge(int src,int dst,Flow lower,Flow upper,Cost cost){
    int e=G[src].size();
    int r=(src==dst?e+1:G[dst].size());
    assert(lower<=upper);
    G[src].emplace_back(src,dst,+upper,+cost*objective,r);
    G[dst].emplace_back(dst,src,-lower,-cost*objective,e);
    return EdgePtr(src,e);
  }

  const Edge &get_edge(EdgePtr ep)const{return G[ep.v][ep.e];}

  void push(Edge &e,Flow amount){
    e.flow+=amount;
    G[e.dst][e.rev].flow-=amount;
  }

  void add_supply(int v,Flow amount){b[v]+=amount;}
  void add_demand(int v,Flow amount){b[v]-=amount;}

  Cost residual_cost(const Edge &e){
    return e.cost+p[e.src]-p[e.dst];
  }

  vector<int> excess_vs,deficit_vs;
  void saturate_negative(const Flow delta){
    for(auto &es:G){
      for(auto &e:es){
        Flow cap=e.residual_cap();
        cap-=cap%delta;
        if(cap<0 or residual_cost(e)<0){
          push(e,cap);
          b[e.src]-=cap;
          b[e.dst]+=cap;
        }
      }
    }

    excess_vs.clear();
    deficit_vs.clear();
    for(int v=0;v<n;v++){
      if(b[v]>0) excess_vs.emplace_back(v);
      if(b[v]<0) deficit_vs.emplace_back(v);
    }
  }

  const Cost unreachable = std::numeric_limits<Cost>::max();
  Cost farthest;
  vector<Cost> dist;
  vector<Edge*> parent;

  struct P{
    Cost first;
    int second;
    P(Cost first,int second):first(first),second(second){}
    bool operator<(const P o)const{return first>o.first;}
  };

  priority_queue<P> pq;

  template<typename Predicate>
  void eliminate(vector<int> &vs,Predicate predicate){
    vs.erase(remove_if(begin(vs),end(vs),predicate),end(vs));
  }

  bool dual(const Flow delta){
    eliminate(excess_vs, [&](int v){return b[v]<+delta;});
    eliminate(deficit_vs,[&](int v){return b[v]>-delta;});

    dist.assign(n,unreachable);
    for(int v:excess_vs) pq.emplace(dist[v]=0,v);

    parent.assign(n,nullptr);
    auto emplace=[&](Edge& e){
      if(e.residual_cap()<delta) return;
      Cost nxt=dist[e.src]+residual_cost(e);
      if(nxt>=dist[e.dst]) return;
      pq.emplace(dist[e.dst]=nxt,e.dst);
      parent[e.dst]=&e;
    };

    farthest=0;
    int deficit_count=0;
    while(!pq.empty()){
      Cost d=pq.top().first;
      int v=pq.top().second;
      pq.pop();
      if(dist[v]<d) continue;
      farthest=d;

      if(b[v]<=-delta) deficit_count++;
      if(deficit_count>=(int)deficit_vs.size()) break;

      for(auto &e:G[v]) emplace(e);
    }
    pq=decltype(pq)();

    for(int v=0;v<n;v++)
      p[v]+=min(dist[v],farthest);

    return deficit_count>0;
  }

  void primal(const Flow delta){
    for(int t:deficit_vs){
      if(dist[t]>farthest) continue;
      Flow f=-b[t];
      int v;
      for(v=t;parent[v];v=parent[v]->src)
        chmin(f,parent[v]->residual_cap());
      chmin(f,b[v]);

      f-=f%delta;
      if(f<=0) continue;

      for(v=t;parent[v];){
        auto &e=*parent[v];
        push(e,f);
        int u=parent[v]->src;
        if(e.residual_cap()<=0) parent[v]=nullptr;
        v=u;
      }
      b[t]+=f;
      b[v]-=f;
    }
  }

  template<Flow SCALING_FACTOR=2>
  bool build(){
    p.resize(n);
    Flow max_flow=1;
    for(auto t:b) max_flow=max({max_flow,t,-t});
    for(auto &es:G)
      for(auto &e:es)
        max_flow=max({max_flow,e.residual_cap(),-e.residual_cap()});

    Flow delta=1;
    while(delta<max_flow) delta*=SCALING_FACTOR;
    for(;delta;delta/=SCALING_FACTOR){
      saturate_negative(delta);
      while(dual(delta)) primal(delta);
    }

    return excess_vs.empty() and deficit_vs.empty();
  }

  template<typename T=Cost>
  T get_cost(){
    T res=0;
    for(auto &es:G)
      for(auto &e:es)
        res+=T(e.flow)*T(e.cost)/T(objective);
    return res/T(2);
  }
  template<typename T=Cost> T get_gain(){return get_cost();}

  vector<Cost> get_potential(){
    fill(p.begin(),p.end(),0);
    for(int i=0;i<n;i++)
      for(auto &es:G)
        for(auto &e:es)
          if(e.residual_cap()>0)
            chmin(p[e.dst],p[e.src]+e.cost);
    return p;
  }
};

template<typename Flow, typename Cost>
using MaxGainFlow = MinCostFlow<Flow, Cost, Objective::MAXIMIZE>;
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  return 0;
}
#endif

#undef call_from_test

signed main(){
  using P = pair<int, int>;
  using ll = long long;
  const ll INF = (1<<30)-1;

  int n,m;
  cin>>n>>m;
  vector< vector<P> > H(n);
  MinCostFlow<ll, ll> G(n);
  for(int i=0;i<m;i++){
    int x,y,s;
    cin>>x>>y>>s;
    H[x].emplace_back(y,s);
    G.add_edge(y,x,1,INF,-s);
  }

  vector<int> dp(n,0);
  for(int i=0;i<n;i++)
    for(auto e:H[i])
      chmax(dp[e.first],dp[i]+e.second);
  G.add_edge(0,n-1,0,INF,dp[n-1]);

  assert(G.build());
  cout<<G.get_cost()<<endl;
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3540
final_rank: 2

code_snippet: #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2230"

#include<bits/stdc++.h>
using namespace std;

#define call_from_test

#ifndef call_from_test
#include <bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif


#ifndef call_from_test
#include <bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
// O(m^2 \log n \log U)
// U: maximum capacity
enum Objective{
  MINIMIZE = +1,
  MAXIMIZE = -1,
};
template<typename Flow, typename Cost,
         Objective objective = Objective::MINIMIZE>
struct MinCostFlow{
  template<typename T> inline void chmin(T &x,T y){x=min(x,y);}

  struct Edge{
    int src,dst;
    Flow flow,cap;
    Cost cost;
    int rev;
    Edge(int src,int dst,Flow cap,Cost cost,int rev):
      src(src),dst(dst),flow(0),cap(cap),cost(cost),rev(rev){}
    Flow residual_cap()const{return cap-flow;}
  };

  struct EdgePtr{
    int v,e;
    EdgePtr(int v,int e):v(v),e(e){}
  };

  int n;
  vector<vector<Edge>> G;
  vector<Flow> b;
  vector<Cost> p;

  MinCostFlow(int n):n(n),G(n),b(n,0){}

  EdgePtr add_edge(int src,int dst,Flow lower,Flow upper,Cost cost){
    int e=G[src].size();
    int r=(src==dst?e+1:G[dst].size());
    assert(lower<=upper);
    G[src].emplace_back(src,dst,+upper,+cost*objective,r);
    G[dst].emplace_back(dst,src,-lower,-cost*objective,e);
    return EdgePtr(src,e);
  }

  const Edge &get_edge(EdgePtr ep)const{return G[ep.v][ep.e];}

  void push(Edge &e,Flow amount){
    e.flow+=amount;
    G[e.dst][e.rev].flow-=amount;
  }

  void add_supply(int v,Flow amount){b[v]+=amount;}
  void add_demand(int v,Flow amount){b[v]-=amount;}

  Cost residual_cost(const Edge &e){
    return e.cost+p[e.src]-p[e.dst];
  }

  vector<int> excess_vs,deficit_vs;
  void saturate_negative(const Flow delta){
    for(auto &es:G){
      for(auto &e:es){
        Flow cap=e.residual_cap();
        cap-=cap%delta;
        if(cap<0 or residual_cost(e)<0){
          push(e,cap);
          b[e.src]-=cap;
          b[e.dst]+=cap;
        }
      }
    }

    excess_vs.clear();
    deficit_vs.clear();
    for(int v=0;v<n;v++){
      if(b[v]>0) excess_vs.emplace_back(v);
      if(b[v]<0) deficit_vs.emplace_back(v);
    }
  }

  const Cost unreachable = std::numeric_limits<Cost>::max();
  Cost farthest;
  vector<Cost> dist;
  vector<Edge*> parent;

  struct P{
    Cost first;
    int second;
    P(Cost first,int second):first(first),second(second){}
    bool operator<(const P o)const{return first>o.first;}
  };

  priority_queue<P> pq;

  template<typename Predicate>
  void eliminate(vector<int> &vs,Predicate predicate){
    vs.erase(remove_if(begin(vs),end(vs),predicate),end(vs));
  }

  bool dual(const Flow delta){
    eliminate(excess_vs, [&](int v){return b[v]<+delta;});
    eliminate(deficit_vs,[&](int v){return b[v]>-delta;});

    dist.assign(n,unreachable);
    for(int v:excess_vs) pq.emplace(dist[v]=0,v);

    parent.assign(n,nullptr);
    auto emplace=[&](Edge& e){
      if(e.residual_cap()<delta) return;
      Cost nxt=dist[e.src]+residual_cost(e);
      if(nxt>=dist[e.dst]) return;
      pq.emplace(dist[e.dst]=nxt,e.dst);
      parent[e.dst]=&e;
    };

    farthest=0;
    int deficit_count=0;
    while(!pq.empty()){
      Cost d=pq.top().first;
      int v=pq.top().second;
      pq.pop();
      if(dist[v]<d) continue;
      farthest=d;

      if(b[v]<=-delta) deficit_count++;
      if(deficit_count>=(int)deficit_vs.size()) break;

      for(auto &e:G[v]) emplace(e);
    }
    pq=decltype(pq)();

    for(int v=0;v<n;v++)
      p[v]+=min(dist[v],farthest);

    return deficit_count>0;
  }

  void primal(const Flow delta){
    for(int t:deficit_vs){
      if(dist[t]>farthest) continue;
      Flow f=-b[t];
      int v;
      for(v=t;parent[v];v=parent[v]->src)
        chmin(f,parent[v]->residual_cap());
      chmin(f,b[v]);

      f-=f%delta;
      if(f<=0) continue;

      for(v=t;parent[v];){
        auto &e=*parent[v];
        push(e,f);
        int u=parent[v]->src;
        if(e.residual_cap()<=0) parent[v]=nullptr;
        v=u;
      }
      b[t]+=f;
      b[v]-=f;
    }
  }

  template<Flow SCALING_FACTOR=2>
  bool build(){
    p.resize(n);
    Flow max_flow=1;
    for(auto t:b) max_flow=max({max_flow,t,-t});
    for(auto &es:G)
      for(auto &e:es)
        max_flow=max({max_flow,e.residual_cap(),-e.residual_cap()});

    Flow delta=1;
    while(delta<max_flow) delta*=SCALING_FACTOR;
    for(;delta;delta/=SCALING_FACTOR){
      saturate_negative(delta);
      while(dual(delta)) primal(delta);
    }

    return excess_vs.empty() and deficit_vs.empty();
  }

  template<typename T=Cost>
  T get_cost(){
    T res=0;
    for(auto &es:G)
      for(auto &e:es)
        res+=T(e.flow)*T(e.cost)/T(objective);
    return res/T(2);
  }
  template<typename T=Cost> T get_gain(){return get_cost();}

  vector<Cost> get_potential(){
    fill(p.begin(),p.end(),0);
    for(int i=0;i<n;i++)
      for(auto &es:G)
        for(auto &e:es)
          if(e.residual_cap()>0)
            chmin(p[e.dst],p[e.src]+e.cost);
    return p;
  }
};

template<typename Flow, typename Cost>
using MaxGainFlow = MinCostFlow<Flow, Cost, Objective::MAXIMIZE>;
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  return 0;
}
#endif

#undef call_from_test

signed main(){
  using P = pair<int, int>;
  using ll = long long;
  const ll INF = 1<<30;

  int n,m;
  cin>>n>>m;
  vector< vector<P> > H(n);
  MinCostFlow<ll, ll> G(n);
  for(int i=0;i<m;i++){
    int x,y,s;
    cin>>x>>y>>s;
    H[x].emplace_back(y,s);
    G.add_edge(y,x,1,INF,-s);
  }

  vector<int> dp(n,0);
  for(int i=0;i<n;i++)
    for(auto e:H[i])
      chmax(dp[e.first],dp[i]+e.second);
  G.add_edge(0,n-1,0,INF,dp[n-1]);

  assert(G.build());
  cout<<G.get_cost()<<endl;
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3508
final_rank: 1

code_snippet: // #define _GLIBCXX_DEBUG // for STL debug (optional)
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>
#include <climits>
#include <ctime>
#include <cassert>
#include <numeric>
#include <fstream>
#include <functional>
#include <bitset>
using namespace std;
using ll = long long int;
using int64 = long long int;
 
template<typename T> void chmax(T &a, T b) {a = max(a, b);}
template<typename T> void chmin(T &a, T b) {a = min(a, b);}
template<typename T> void chadd(T &a, T b) {a = a + b;}
 
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const int INF = 1LL << 29;
const ll LONGINF = 1LL << 60;
const ll MOD = 1000000007LL;

// Ford-Fulkerson 法による 最大流 O( F |E| )
// Bellman-Ford 法による 最小費用流 O( F |V| |E| )
// [条件に注意] Dijkstra 法による 最小費用流 O( F |E| log |V| )

template <typename CapTp=int, typename CostTp=int>
struct Edge {
    int to, rev;
    CapTp cap; CostTp cost;
    bool is_rev;
    Edge(int t, bool f, int r, CapTp ca, CostTp co=0)
        : to(t), rev(r), cap(ca), cost(co), is_rev(f) {}
};

template <typename CapTp=int, typename CostTp=int>
struct Flow {
    using Graph = vector< vector< Edge<CapTp, CostTp> > >;
    Graph G; const CapTp IA; const CostTp IO, NIL;
    vector< pair<int, int> > r_edges;
    Flow(int N_, CapTp IA_=1<<29, CostTp IO_=1<<29, CostTp NIL_=-1)
        : G(N_), IA(IA_), IO(IO_), NIL(NIL_), r_edges() {}
    // 辺を追加 (from -> to に流量 ca, コスト co)
    void add_edge(int from, int to, CapTp ca, CostTp co=0) {
        G[from].emplace_back(to, false, G[to].size(), ca, co);
        G[to].emplace_back(from, true, G[from].size() - 1, 0, -co);
        r_edges.emplace_back(to, G[to].size() - 1);
    }
    // k 番目の辺にいくつ流れたか
    CapTp get_flowed_cap(size_t k) {
        if(r_edges.size() <= k) return -1;
        int v, i; tie(v, i) = r_edges[k];
        return G[v][i].cap;
    }
    // s -> t 最大流
    CapTp max_flow(int s, int t) {
        vector<bool> used(G.size());
        auto dfs = [&](auto &&func, int v, int t, CapTp f) -> CapTp {
            if(v == t) return f;
            used[v] = true;
            for(auto &e : G[v]) {
                if(used[e.to] or e.cap == 0) continue;
                CapTp d = func(func, e.to, t, min(f, e.cap));
                if(d == 0) continue;
                e.cap -= d; G[e.to][e.rev].cap += d;
                return d;
            }
            return 0;
        };

        CapTp res(0);
        while(true) {
            fill(used.begin(), used.end(), false);
            CapTp delta = dfs(dfs, s, t, IA);
            if(delta == 0) return res;
            res += delta;
        }
    }
    // ベルマンフォードをつかって最小費用流
    CostTp mincost_flow(int s, int t, CapTp f) {
        vector<CostTp> dist(G.size()); CostTp res(0);
        vector<int> prevv(G.size()), preve(G.size());
        while(f > 0) {
            fill(dist.begin(), dist.end(), IO);
            dist[s] = 0;
            while(1) {
                bool upd = false;
                for(int v=0; v<(int)G.size(); v++) {
                    if(dist[v] == IO) continue;
                    for(size_t i=0; i<G[v].size(); i++) {
                        auto &e = G[v][i];
                        if(e.cap == 0 or dist[e.to] <= dist[v] + e.cost) continue;
                        dist[e.to] = dist[v] + e.cost;
                        prevv[e.to] = v, preve[e.to] = i;
                        upd = true;
                    }
                }
                if(!upd) break;
            }

            if(dist[t] == IO) return NIL;
            CapTp d = f;
            for(int v=t; v!=s; v=prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap);
            f -= d; res += d * dist[t];
            for(int v=t; v!=s; v=prevv[v]) {
                auto &e = G[prevv[v]][preve[v]];
                e.cap -= d, G[v][e.rev].cap += d;
            }
        }
        return res;
    }
    // ポテンシャルの導入により、ダイクストラ法で最小費用流を解く
    // [仮定している条件]
    //     1. グラフに負の閉路が存在しない (流量の 0 初期化のため)
    //        もし存在するならベルマンフォードで負の閉路を見つけ
    //        そこに流せるだけ流してスタート
    //     2. グラフに負の辺が存在しない (pot_0 の計算可能性)
    //        もし存在する場合は最初のみベルマンフォードを使う必要あり
    CostTp fast_mincost_flow(int s, int t, CapTp f) {
        CostTp res = 0;
        vector<CostTp> dist(G.size()), pot(G.size());
        vector<int> prevv(G.size()), preve(G.size());
        while(f > 0) {
            using PT = pair<CostTp, int>;
            priority_queue< PT, vector<PT>, greater<PT> > que;
            fill(dist.begin(), dist.end(), IO);

            dist[s] = 0;
            que.push(make_pair(0, s));
            while(!que.empty()) {
                PT cur = que.top(); que.pop();
                int v = cur.second;
                if(dist[v] < cur.first) continue;
                for(size_t i=0; i<G[v].size(); i++) {
                    auto& e = G[v][i];
                    if(e.cap > 0 and dist[e.to] > dist[v] + e.cost + pot[v] - pot[e.to]) {
                        dist[e.to] = dist[v] + e.cost + pot[v] - pot[e.to];
                        prevv[e.to] = v;
                        preve[e.to] = i;
                        que.push(make_pair(dist[e.to], e.to));
                    }
                }
            }
            if(dist[t] == IO) {
                return NIL;
            }
            for(int v=0; v<(int)G.size(); v++) pot[v] += dist[v];

            CapTp d = f;
            for(int v=t; v!=s; v=prevv[v]) {
                d = min(d, G[prevv[v]][preve[v]].cap);
            }
            f -= d;
            res += d * pot[t];
            for(int v=t; v!=s; v=prevv[v]) {
                auto& e = G[prevv[v]][preve[v]];
                e.cap -= d;
                G[v][e.rev].cap += d;
            }
        }
        return res;
    }    
};

template <typename cap_tp=int, typename cost_tp=int,
          template<typename, typename> class flow_fw=Flow>
struct GeneralizedMincostFlow {
private:
    flow_fw<cap_tp, cost_tp> fl;
    vector<cap_tp> D;
    int N, source, sink;
    cap_tp Z_cap;
    cost_tp Z_cost, ofs, ng;

public:
    GeneralizedMincostFlow(int N_, cost_tp ng_=-1,
                           cap_tp zero_cap=0, cost_tp zero_cost=0)
        : fl(N_+2), D(N_), N(N_), source(N_), sink(N_+1),
          Z_cap(zero_cap), Z_cost(zero_cost), ofs(zero_cost), ng(ng_) {}

    void add_edge(int u, int v, cap_tp low, cap_tp high, cost_tp cost) {
        assert(low <= high);
        // コストが負の場合
        if(cost < Z_cost) {
            // 流すだけ得なので high 流れたことにする
            ofs += high * cost;
            D[u] -= high; D[v] += high;
            // 目一杯流したのを high - low 分だけキャンセル可能
            if(high - low > Z_cap) {
                fl.add_edge(v, u, high - low, -cost);
            }
        }
        else {
            // v 側に low 流れたことにする
            ofs += low * cost;
            D[u] -= low; D[v] += low;
            // high - low 分の辺を張る
            if(high - low > Z_cap) {
                fl.add_edge(u, v, high - low, cost);
            }
        }
    }
    void add_edge(int u, int v, cap_tp cap, cost_tp cost) {
        add_edge(u, v, Z_cap, cap, cost);
    }
    void change_d(int u, cap_tp delta) {
        D[u] += delta;
    }
    
    cost_tp mincost_flow() {
        cap_tp sum_d = 0;
        for(int i=0; i<N; i++) {
            if(D[i] > 0) {
                fl.add_edge(source, i, D[i], 0);
                sum_d += D[i];
            }
            else {
                fl.add_edge(i, sink, -D[i], 0);
            }
        }

        cost_tp res = fl.mincost_flow(source, sink, sum_d);
        if(res == fl.NIL) return ng;
        else return ofs + res;
    }
};

int main() {
    int N, M; scanf("%d%d", &N, &M);
    GeneralizedMincostFlow<ll, ll> fl(N);
    vector< vector< pair<int, int> > > G(N);
    for(int i=0; i<M; i++) {
        int u, v, s;
        scanf("%d%d%d", &u, &v, &s);
        G[u].emplace_back(v, s);
        fl.add_edge(v, u, 1, INF, -s);
    }
    vector<int> dist(N);
    for(int i=0; i<N; i++) {
        for(auto e : G[i]) {
            int j, c; tie(j, c) = e;
            chmax(dist[j], dist[i] + c);
        }
    }
    fl.add_edge(0, N-1, 0, INF, dist[N-1]);
    
    printf("%d\n", fl.mincost_flow());
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 3324
final_rank: 15

code_snippet: // #define _GLIBCXX_DEBUG // for STL debug (optional)
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>
#include <climits>
#include <ctime>
#include <cassert>
#include <numeric>
#include <fstream>
#include <functional>
#include <bitset>
using namespace std;
using ll = long long int;
using int64 = long long int;
 
template<typename T> void chmax(T &a, T b) {a = max(a, b);}
template<typename T> void chmin(T &a, T b) {a = min(a, b);}
template<typename T> void chadd(T &a, T b) {a = a + b;}
 
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const int INF = 1LL << 29;
const ll LONGINF = 1LL << 60;
const ll MOD = 1000000007LL;

// Ford-Fulkerson 法による 最大流 O( F |E| )
// Bellman-Ford 法による 最小費用流 O( F |V| |E| )
// [条件に注意] Dijkstra 法による 最小費用流 O( F |E| log |V| )

template <typename CapTp=int, typename CostTp=int>
struct Edge {
    int to, rev;
    CapTp cap; CostTp cost;
    bool is_rev;
    Edge(int t, bool f, int r, CapTp ca, CostTp co=0)
        : to(t), rev(r), cap(ca), cost(co), is_rev(f) {}
};

template <typename CapTp=int, typename CostTp=int>
struct Flow {
    using Graph = vector< vector< Edge<CapTp, CostTp> > >;
    Graph G; const CapTp IA; const CostTp IO, NIL;
    vector< pair<int, int> > r_edges;
    Flow(int N_, CapTp IA_=1<<29, CostTp IO_=1<<29, CostTp NIL_=-1)
        : G(N_), IA(IA_), IO(IO_), NIL(NIL_), r_edges() {}
    // 辺を追加 (from -> to に流量 ca, コスト co)
    void add_edge(int from, int to, CapTp ca, CostTp co=0) {
        G[from].emplace_back(to, false, G[to].size(), ca, co);
        G[to].emplace_back(from, true, G[from].size() - 1, 0, -co);
        r_edges.emplace_back(to, G[to].size() - 1);
    }
    // k 番目の辺にいくつ流れたか
    CapTp get_flowed_cap(size_t k) {
        if(r_edges.size() <= k) return -1;
        int v, i; tie(v, i) = r_edges[k];
        return G[v][i].cap;
    }
    // s -> t 最大流
    CapTp max_flow(int s, int t) {
        vector<bool> used(G.size());
        auto dfs = [&](auto &&func, int v, int t, CapTp f) -> CapTp {
            if(v == t) return f;
            used[v] = true;
            for(auto &e : G[v]) {
                if(used[e.to] or e.cap == 0) continue;
                CapTp d = func(func, e.to, t, min(f, e.cap));
                if(d == 0) continue;
                e.cap -= d; G[e.to][e.rev].cap += d;
                return d;
            }
            return 0;
        };

        CapTp res(0);
        while(true) {
            fill(used.begin(), used.end(), false);
            CapTp delta = dfs(dfs, s, t, IA);
            if(delta == 0) return res;
            res += delta;
        }
    }
    // ベルマンフォードをつかって最小費用流
    CostTp mincost_flow(int s, int t, CapTp f) {
        vector<CostTp> dist(G.size()); CostTp res(0);
        vector<int> prevv(G.size()), preve(G.size());
        while(f > 0) {
            fill(dist.begin(), dist.end(), IO);
            dist[s] = 0;
            while(1) {
                bool upd = false;
                for(int v=0; v<(int)G.size(); v++) {
                    if(dist[v] == IO) continue;
                    for(size_t i=0; i<G[v].size(); i++) {
                        auto &e = G[v][i];
                        if(e.cap == 0 or dist[e.to] <= dist[v] + e.cost) continue;
                        dist[e.to] = dist[v] + e.cost;
                        prevv[e.to] = v, preve[e.to] = i;
                        upd = true;
                    }
                }
                if(!upd) break;
            }

            if(dist[t] == IO) return NIL;
            CapTp d = f;
            for(int v=t; v!=s; v=prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap);
            f -= d; res += d * dist[t];
            for(int v=t; v!=s; v=prevv[v]) {
                auto &e = G[prevv[v]][preve[v]];
                e.cap -= d, G[v][e.rev].cap += d;
            }
        }
        return res;
    }
    // ポテンシャルの導入により、ダイクストラ法で最小費用流を解く
    // [仮定している条件]
    //     1. グラフに負の閉路が存在しない (流量の 0 初期化のため)
    //        もし存在するならベルマンフォードで負の閉路を見つけ
    //        そこに流せるだけ流してスタート
    //     2. グラフに負の辺が存在しない (pot_0 の計算可能性)
    //        もし存在する場合は最初のみベルマンフォードを使う必要あり
    CostTp fast_mincost_flow(int s, int t, CapTp f) {
        CostTp res = 0;
        vector<CostTp> dist(G.size()), pot(G.size());
        vector<int> prevv(G.size()), preve(G.size());
        while(f > 0) {
            using PT = pair<CostTp, int>;
            priority_queue< PT, vector<PT>, greater<PT> > que;
            fill(dist.begin(), dist.end(), IO);

            dist[s] = 0;
            que.push(make_pair(0, s));
            while(!que.empty()) {
                PT cur = que.top(); que.pop();
                int v = cur.second;
                if(dist[v] < cur.first) continue;
                for(size_t i=0; i<G[v].size(); i++) {
                    auto& e = G[v][i];
                    if(e.cap > 0 and dist[e.to] > dist[v] + e.cost + pot[v] - pot[e.to]) {
                        dist[e.to] = dist[v] + e.cost + pot[v] - pot[e.to];
                        prevv[e.to] = v;
                        preve[e.to] = i;
                        que.push(make_pair(dist[e.to], e.to));
                    }
                }
            }
            if(dist[t] == IO) {
                return NIL;
            }
            for(int v=0; v<(int)G.size(); v++) pot[v] += dist[v];

            CapTp d = f;
            for(int v=t; v!=s; v=prevv[v]) {
                d = min(d, G[prevv[v]][preve[v]].cap);
            }
            f -= d;
            res += d * pot[t];
            for(int v=t; v!=s; v=prevv[v]) {
                auto& e = G[prevv[v]][preve[v]];
                e.cap -= d;
                G[v][e.rev].cap += d;
            }
        }
        return res;
    }    
};

template <typename cap_tp=int, typename cost_tp=int,
          template<typename, typename> class flow_fw=Flow>
struct GeneralizedMincostFlow {
private:
    flow_fw<cap_tp, cost_tp> fl;
    vector<cap_tp> D;
    int N, source, sink;
    cap_tp Z_cap;
    cost_tp Z_cost, ofs, ng;

public:
    GeneralizedMincostFlow(int N_, cost_tp ng_=-1,
                           cap_tp zero_cap=0, cost_tp zero_cost=0)
        : fl(N_+2), D(N_), N(N_), source(N_), sink(N_+1),
          Z_cap(zero_cap), Z_cost(zero_cost), ofs(zero_cost), ng(ng_) {}

    void add_edge(int u, int v, cap_tp low, cap_tp high, cost_tp cost) {
        assert(low <= high);
        // コストが負の場合
        if(cost < Z_cost) {
            // 流すだけ得なので high 流れたことにする
            ofs += high * cost;
            D[u] -= high; D[v] += high;
            // 目一杯流したのを high - low 分だけキャンセル可能
            if(high - low > Z_cap) {
                fl.add_edge(v, u, high - low, -cost);
            }
        }
        else {
            // v 側に low 流れたことにする
            ofs += low * cost;
            D[u] -= low; D[v] += low;
            // high - low 分の辺を張る
            if(high - low > Z_cap) {
                fl.add_edge(u, v, high - low, cost);
            }
        }
    }
    void add_edge(int u, int v, cap_tp cap, cost_tp cost) {
        add_edge(u, v, Z_cap, cap, cost);
    }
    void change_d(int u, cap_tp delta) {
        D[u] += delta;
    }
    
    cost_tp mincost_flow() {
        cap_tp sum_d = 0;
        for(int i=0; i<N; i++) {
            if(D[i] > 0) {
                fl.add_edge(source, i, D[i], 0);
                sum_d += D[i];
            }
            else {
                fl.add_edge(i, sink, -D[i], 0);
            }
        }

        cost_tp res = fl.mincost_flow(source, sink, sum_d);
        if(res == fl.NIL) return ng;
        else return ofs + res;
    }
};

int main() {
    int N, M; scanf("%d%d", &N, &M);
    GeneralizedMincostFlow<ll, ll> fl(N);
    vector< vector< pair<int, int> > > G(N);
    for(int i=0; i<M; i++) {
        int u, v, s;
        scanf("%d%d%d", &u, &v, &s);
        G[u].emplace_back(v, s);
        fl.add_edge(u, v, 1, INF, -s);
    }
    vector<int> dist(N);
    for(int i=0; i<N; i++) {
        for(auto e : G[i]) {
            int j, c; tie(j, c) = e;
            chmax(dist[j], dist[i] + c);
        }
    }
    fl.add_edge(N-1, 0, 0, INF, dist[N-1]);
    
    printf("%d\n", fl.mincost_flow());
    return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 3324
final_rank: 16

code_snippet: #include <bits/stdc++.h>
 
//    #include <boost/multiprecision/cpp_int.hpp>
 #define int long long
 #define inf  1000000007
 #define pa pair<int,int>
 #define ll long long
 #define pal pair<double,double>
 #define ppap pair<pa,int>
  #define PI 3.14159265358979323846
  #define paa pair<int,char>
  #define  mp make_pair
  #define  pb push_back
  #define EPS (1e-8)
                                          
    int dx[8]={0,1,0,-1,1,1,-1,-1};
    int dy[8]={1,0,-1,0,-1,1,1,-1};
                                            using namespace std;
                                   			class pa3{
                                            	public:
                                            	int x;
                                   				int y,z;
                                            	pa3(int x=0,int y=0,int z=0):x(x),y(y),z(z) {}
                                            	bool operator < (const pa3 &p) const{
                                            		if(x!=p.x) return x<p.x;
                                            		if(y!=p.y) return y<p.y;
                                            		 return z<p.z;
                                            		//return x != p.x ? x<p.x: y<p.y;
                                            	}
                                   				bool operator > (const pa3 &p) const{
                                            		if(x!=p.x) return x>p.x;
                                            		if(y!=p.y) return y>p.y;
                                            		 return z>p.z;
                                            		//return x != p.x ? x<p.x: y<p.y;
                                            	}
                                            	bool operator == (const pa3 &p) const{
                                            		return x==p.x && y==p.y && z==p.z;
                                            	}
                                            		bool operator != (const pa3 &p) const{
                                            			return !( x==p.x && y==p.y && z==p.z);
                                            	}
                                            
                                            };
                                            
                                            class pa4{
                                            	public:
                                            	int x;
                                            	int y,z,w;
                                            	pa4(int x=0,int y=0,int z=0,int w=0):x(x),y(y),z(z),w(w) {}
                                            	bool operator < (const pa4 &p) const{
                                            		if(x!=p.x) return x<p.x;
                                            		if(y!=p.y) return y<p.y;
                                            		if(z!=p.z)return z<p.z;
                                            		return w<p.w;
                                            		//return x != p.x ? x<p.x: y<p.y;
                                            	}
                                            	bool operator > (const pa4 &p) const{
                                            		if(x!=p.x) return x>p.x;
                                            		if(y!=p.y) return y>p.y;
                                            		if(z!=p.z)return z>p.z;
                                            		return w>p.w;
                                            		//return x != p.x ? x<p.x: y<p.y;
                                            	}
                                            	bool operator == (const pa4 &p) const{
                                            		return x==p.x && y==p.y && z==p.z &&w==p.w;
                                            	}
                                            		
                                            
                                            };
                                            class pa2{
                                            	public:
                                            	int x,y;
                                            	pa2(int x=0,int y=0):x(x),y(y) {}
                                            	pa2 operator + (pa2 p) {return pa2(x+p.x,y+p.y);}
                                            	pa2 operator - (pa2 p) {return pa2(x-p.x,y-p.y);}
                                            	bool operator < (const pa2 &p) const{
                                            		return y != p.y ? y<p.y: x<p.x;
                                            	}
                                            	bool operator > (const pa2 &p) const{
                                            		return x != p.x ? x<p.x: y<p.y;
                                            	}
                                            	bool operator == (const pa2 &p) const{
                                            		return abs(x-p.x)==0 && abs(y-p.y)==0;
                                            	}
                                            	bool operator != (const pa2 &p) const{
                                            		return !(abs(x-p.x)==0 && abs(y-p.y)==0);
                                            	}
                                            		
                                            
                                            };
                                            
 
                      
                                string itos( int i ) {
                                ostringstream s ;
                                s << i ;
                                return s.str() ;
                                }
                                 
                                int gcd(int v,int b){
                                	if(v==0) return b;
                                	if(b==0) return v;
                                	if(v>b) return gcd(b,v);
                                	if(v==b) return b;
                                	if(b%v==0) return v;
                                	return gcd(v,b%v);
                                }
                 
                            
                                int mod;
int extgcd(int a, int b, int &x, int &y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    int d = extgcd(b, a%b, y, x);
    y -= a/b * x;
    return d;
}
pa operator+(const pa & l,const pa & r) {   
    return {l.first+r.first,l.second+r.second};                                    
}    
pa operator-(const pa & l,const pa & r) {   
    return {l.first-r.first,l.second-r.second};                                    
}  
                int beki(int wa,int rr,int warukazu){
                	if(rr==0) return 1%warukazu;
                	if(rr==1) return wa%warukazu;
                	wa%=warukazu;
                	if(rr%2==1) return ((ll)beki(wa,rr-1,warukazu)*(ll)wa)%warukazu;
                	ll zx=beki(wa,rr/2,warukazu);
                	return (zx*zx)%warukazu;
                }
 
                              
                int pr[1000100];
                int inv[1000010];
                

                
    			int comb(int nn,int rr){
    				if(rr<0 || rr>nn || nn<0) return 0;
    				int r=pr[nn]*inv[rr];
    				r%=mod;
    				r*=inv[nn-rr];
    				r%=mod;
    				return r;
    			}
               
                void gya(int ert){
                	pr[0]=1;
                	for(int i=1;i<=ert;i++){
                		pr[i]=((ll)pr[i-1]*i)%mod;
                	}
                		inv[ert]=beki(pr[ert],mod-2,mod);
                	for(int i=ert-1;i>=0;i--){
                		inv[i]=(ll)inv[i+1]*(i+1)%mod;
                	}
                }
                
              //   cin.tie(0);
    		//	ios::sync_with_stdio(false);
    			//priority_queue<pa3,vector<pa3>,greater<pa3>> pq;            
                 //sort(ve.begin(),ve.end(),greater<int>());
 //   mt19937(clock_per_sec);
  //  mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()) ;

typedef pair<int,int> P;
struct edge{ int to,cap,cost,rev;};
vector<edge> G[100010];
bool used[100010];
int h[100010],dist[100010],prevv[100010],preve[100010];
int V;//Vは頂点数

void add_edge(int from,int to,int cap,int cost){
	G[from].push_back( (edge){to,cap,cost,(int)G[to].size()} );
		G[to].push_back( (edge){from,0,-cost,(int)G[from].size()-1 });
}

int min_cost_flow(int s,int t,int f){
	int res=0;
	fill(h,h+V,0);
	while(f>0){
		priority_queue <P,vector<P>,greater<P> > que;
		fill(dist,dist+V,inf);
		dist[s]=0;
		que.push(P(0,s));
		while( !que.empty() ){
			P p=que.top();que.pop();
			int v=p.second;
			if(dist[v]<p.first) continue;
			for(int i=0;i<(int)G[v].size();i++){
				edge &e=G[v][i];
				if(e.cap>0 && dist[e.to]>dist[v]+e.cost+h[v]-h[e.to]){
					dist[e.to]=dist[v]+e.cost+h[v]-h[e.to];
					prevv[e.to]=v;
					preve[e.to]=i;
					que.push(P(dist[e.to],e.to));
				}
			}
		}
	if(dist[t]==inf) return -1;
	for(int v=0;v<V;v++)h[v] += dist[v];
	int d=f;
	for(int v=t;v!=s;v=prevv[v]){
		d=min(d,G[prevv[v]][preve[v]].cap);
	}
	f -= d;
	res += d*h[t];
	for(int v=t; v!=s;v=prevv[v]){
		edge &e =G[prevv[v]][preve[v]];
		e.cap -=d;
		G[v][e.rev].cap +=d;
	}
}
return res;
}

vector<pa> F[2020];
int dis[2020]={};
int wei[1021]={};
signed main(){
cin.tie(0);
ios::sync_with_stdio(false);

	int n,m;
	cin>>n>>m;
	V=n+100;
	int Q=30000;
	int W=0;
	for(int i=0;i<m;i++){
		int u,v,w;
		cin>>u>>v>>w;
		W+=w;
		wei[u]++;
		wei[v]--;
		F[v].pb(mp(u,w));
		wei[u]+=Q;
		wei[v]-=Q;
		add_edge(u,v,Q,w);
	
	}
	
	
	dis[0]=0;
	for(int i=1;i<n;i++){
		for(auto v:F[i])dis[i]=max(dis[i],dis[v.first]+v.second);
	}
	
	add_edge(0,n-1,Q,dis[n-1]);
	int s=0;
	for(int i=0;i<n;i++){
		if(wei[i]>0){
			add_edge(n,i,wei[i],0);
			s+=wei[i];
		}
		
		if(wei[i]<0) add_edge(i,n+1,-wei[i],0);
		
	}
	cout<<min_cost_flow(n,n+1,s)-Q*W-W<<endl;
	//int ans=-(min_cost_flow(n,n+1,s)+W);
	//cout<<ans<<endl;
	
	
		return 0;
 }
accuracy: 1
time_ms: 20
memory_kb: 5692
final_rank: 14

code_snippet: #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,m,n) for(int i=(m);i<(n);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
using ll = long long;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-8;
const int MOD = 1000000007;
// const int MOD = 998244353;
const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1};
const int dy8[] = {1, 1, 0, -1, -1, -1, 0, 1}, dx8[] = {0, -1, -1, -1, 0, 1, 1, 1};
template <typename T, typename U> inline bool chmax(T &a, U b) { return a < b ? (a = b, true) : false; }
template <typename T, typename U> inline bool chmin(T &a, U b) { return a > b ? (a = b, true) : false; }
struct IOSetup {
  IOSetup() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);
  }
} iosetup;

template <typename T, typename U>
struct PrimalDual2 {
  using Pui = pair<U, int>;

  struct Edge {
    int dst, rev;
    T cap;
    U cost;
    Edge(int dst, T cap, U cost, int rev) : dst(dst), cap(cap), cost(cost), rev(rev) {}
  };

  vector<vector<Edge> > graph;

  PrimalDual2(int n, const T TINF, const U UINF) : n(n), UINF(UINF), graph(n + 2), d(n + 2, 0) {}

  void add_edge(int src, int dst, T cap, U cost) {
    if (cost < 0) {
      d[src] -= cap;
      d[dst] += cap;
      res += cost * cap;
      swap(src, dst);
      cost = -cost;
    }
    graph[src].emplace_back(dst, cap, cost, graph[dst].size());
    graph[dst].emplace_back(src, 0, -cost, graph[src].size() - 1);
  }

  U minimum_cost_flow() {
    T flow = 0;
    REP(i, n) {
      if (d[i] > 0) {
        add_edge(n, i, d[i], 0);
        flow += d[i];
      } else if (d[i] < 0) {
        add_edge(i, n + 1, -d[i], 0);
      }
    }
    vector<int> prev_v(n + 2, -1), prev_e(n + 2, -1);
    vector<U> potential(n + 2, 0), dist(n + 2);
    priority_queue<Pui, vector<Pui>, greater<Pui> > que;
    while (flow > 0) {
      fill(ALL(dist), UINF);
      dist[n] = 0;
      que.emplace(0, n);
      while (!que.empty()) {
        U fst; int ver; tie(fst, ver) = que.top(); que.pop();
        if (dist[ver] < fst) continue;
        REP(i, graph[ver].size()) {
          Edge &e = graph[ver][i];
          U nx = dist[ver] + e.cost + potential[ver] - potential[e.dst];
          if (e.cap > 0 && dist[e.dst] > nx) {
            dist[e.dst] = nx;
            prev_v[e.dst] = ver;
            prev_e[e.dst] = i;
            que.emplace(dist[e.dst], e.dst);
          }
        }
      }
      if (dist[n + 1] == UINF) return UINF;
      REP(i, n + 2) {
        if (dist[i] != UINF) potential[i] += dist[i];
      }
      T f = flow;
      for (int v = n + 1; v != n; v = prev_v[v]) chmin(f, graph[prev_v[v]][prev_e[v]].cap);
      flow -= f;
      res += potential[n + 1] * f;
      for (int v = n + 1; v != n; v = prev_v[v]) {
        Edge &e = graph[prev_v[v]][prev_e[v]];
        e.cap -= f;
        graph[v][e.rev].cap += f;
      }
    }
    return res;
  }

  U minimum_cost_flow(int s, int t, T flow) {
    d[s] += flow;
    d[t] -= flow;
    return minimum_cost_flow();
  }

private:
  int n;
  const U UINF;
  U res = 0;
  vector<T> d;
};

template <template <typename, typename> class C, typename T, typename U>
struct MinimumCostFlowWithMinimumFlowConstraint {
  MinimumCostFlowWithMinimumFlowConstraint(int n, const U M, const T TINF, const U UINF) : M(M), UINF(UINF), pd(n, TINF, UINF) {}

  void add_edge(int src, int dst, T lb, T ub, U cost) {
    pd.add_edge(src, dst, ub - lb + 1, cost);
    pd.add_edge(src, dst, lb, cost - M);
    lb_sum += lb;
  }

  U solve(int s, int t, T flow) {
    U tmp = pd.minimum_cost_flow(s, t, flow);
    if (tmp == UINF) return UINF;
    return tmp + M * lb_sum;
  }

private:
  const U M, UINF;
  T lb_sum = 0;
  C<T, U> pd;
};

using CostType = ll;
struct Edge {
  int src, dst; CostType cost;
  Edge(int src, int dst, CostType cost = 0) : src(src), dst(dst), cost(cost) {}
  inline bool operator<(const Edge &rhs) const {
    return cost != rhs.cost ? cost < rhs.cost : dst != rhs.dst ? dst < rhs.dst : src < rhs.src;
  }
  inline bool operator<=(const Edge &rhs) const { return !(rhs < *this); }
  inline bool operator>(const Edge &rhs) const { return rhs < *this; }
  inline bool operator>=(const Edge &rhs) const { return !(*this < rhs); }
};

int main() {
  int n, m; cin >> n >> m;
  MinimumCostFlowWithMinimumFlowConstraint<PrimalDual2, ll, ll> pd(n, INF, INF, LINF);
  vector<vector<Edge> > graph(n);
  while (m--) {
    int x, y, s; cin >> x >> y >> s;
    pd.add_edge(y, x, 1, INF, -s);
    graph[x].emplace_back(x, y, s);
  }
  vector<ll> dp(n, 0);
  for (int i = n - 2; i >= 0; --i) {
    for (const Edge &e : graph[i]) chmax(dp[i], dp[e.dst] + e.cost);
  }
  pd.add_edge(0, n - 1, 0, INF, dp[0]);
  cout << pd.solve(0, 0, 0) << '\n';
  return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3276
final_rank: 12

code_snippet: #include <bits/stdc++.h>

using namespace std;

using int64 = long long;
const int mod = 1e9 + 7;
// const int mod = 998244353;

const int64 infll = (1LL << 62) - 1;
const int inf = (1 << 30) - 1;

struct IoSetup {
  IoSetup() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);
    cerr << fixed << setprecision(10);
  }
} iosetup;


template< typename T1, typename T2 >
ostream &operator<<(ostream &os, const pair< T1, T2 > &p) {
  os << p.first << " " << p.second;
  return os;
}

template< typename T1, typename T2 >
istream &operator>>(istream &is, pair< T1, T2 > &p) {
  is >> p.first >> p.second;
  return is;
}

template< typename T >
ostream &operator<<(ostream &os, const vector< T > &v) {
  for(int i = 0; i < (int) v.size(); i++) {
    os << v[i] << (i + 1 != v.size() ? " " : "");
  }
  return os;
}

template< typename T >
istream &operator>>(istream &is, vector< T > &v) {
  for(T &in : v) is >> in;
  return is;
}

template< typename T1, typename T2 >
inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }

template< typename T1, typename T2 >
inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }

template< typename T = int64 >
vector< T > make_v(size_t a) {
  return vector< T >(a);
}

template< typename T, typename... Ts >
auto make_v(size_t a, Ts... ts) {
  return vector< decltype(make_v< T >(ts...)) >(a, make_v< T >(ts...));
}

template< typename T, typename V >
typename enable_if< is_class< T >::value == 0 >::type fill_v(T &t, const V &v) {
  t = v;
}

template< typename T, typename V >
typename enable_if< is_class< T >::value != 0 >::type fill_v(T &t, const V &v) {
  for(auto &e : t) fill_v(e, v);
}

template< typename F >
struct FixPoint : F {
  FixPoint(F &&f) : F(forward< F >(f)) {}

  template< typename... Args >
  decltype(auto) operator()(Args &&... args) const {
    return F::operator()(*this, forward< Args >(args)...);
  }
};

template< typename F >
inline decltype(auto) MFP(F &&f) {
  return FixPoint< F >{forward< F >(f)};
}

template< typename flow_t, typename cost_t >
struct edge {
  int src, to;
  flow_t low, high;
  cost_t cost;

  edge() = default;

  edge(int src, int to, flow_t high, cost_t cost) : src(src), to(to), low(0), high(high), cost(cost) {}

  edge(int src, int to, flow_t low, flow_t high, cost_t cost) : src(src), to(to), low(low), high(high), cost(cost) {}
};

template< typename flow_t, typename cost_t, template< typename, typename > class MF, cost_t NG = -1 >
cost_t normalized_min_cost_flow(vector< flow_t > D, const vector< edge< flow_t, cost_t > > &E) {
  const int N = (int) D.size(), M = (int) E.size();
  MF< flow_t, cost_t > flow(N + 2);
  const int S = N, T = N + 1;


  cost_t sum = 0;
  for(auto &e : E) {
    if(e.cost < 0) {
      sum += e.cost * e.high;
      D[e.src] -= e.high;
      D[e.to] += e.high;
      flow.add_edge(e.to, e.src, e.high - e.low, -e.cost);
    } else {
      sum += e.cost * e.low;
      D[e.src] -= e.low;
      D[e.to] += e.low;
      flow.add_edge(e.src, e.to, e.high - e.low, e.cost);
    }
  }

  flow_t in = 0, out = 0;
  for(int i = 0; i < N; i++) {
    if(D[i] > 0) {
      flow.add_edge(S, i, D[i], flow_t(0));
      in += D[i];
    } else if(D[i] < 0) {
      flow.add_edge(i, T, -D[i], flow_t(0));
      out += -D[i];
    }
  }

  assert(in == out);
  auto ret = flow.min_cost_flow(S, T, in);
  if(ret == -1) return NG;
  return ret + sum;
}

template< typename flow_t, typename cost_t >
struct PrimalDual {
  const cost_t INF;

  struct edge {
    int to;
    flow_t cap;
    cost_t cost;
    int rev;
    bool isrev;
  };
  vector< vector< edge > > graph;
  vector< cost_t > potential, min_cost;
  vector< int > prevv, preve;

  PrimalDual(int V) : graph(V), INF(numeric_limits< cost_t >::max()) {}

  void add_edge(int from, int to, flow_t cap, cost_t cost) {
    graph[from].emplace_back((edge) {to, cap, cost, (int) graph[to].size(), false});
    graph[to].emplace_back((edge) {from, 0, -cost, (int) graph[from].size() - 1, true});
  }

  cost_t min_cost_flow(int s, int t, flow_t f) {
    int V = (int) graph.size();
    cost_t ret = 0;
    using Pi = pair< cost_t, int >;
    priority_queue< Pi, vector< Pi >, greater< Pi > > que;
    potential.assign(V, 0);
    preve.assign(V, -1);
    prevv.assign(V, -1);

    while(f > 0) {
      min_cost.assign(V, INF);
      que.emplace(0, s);
      min_cost[s] = 0;
      while(!que.empty()) {
        Pi p = que.top();
        que.pop();
        if(min_cost[p.second] < p.first) continue;
        for(int i = 0; i < graph[p.second].size(); i++) {
          edge &e = graph[p.second][i];
          cost_t nextCost = min_cost[p.second] + e.cost + potential[p.second] - potential[e.to];
          if(e.cap > 0 && min_cost[e.to] > nextCost) {
            min_cost[e.to] = nextCost;
            prevv[e.to] = p.second, preve[e.to] = i;
            que.emplace(min_cost[e.to], e.to);
          }
        }
      }
      if(min_cost[t] == INF) return -1;
      for(int v = 0; v < V; v++) potential[v] += min_cost[v];
      flow_t addflow = f;
      for(int v = t; v != s; v = prevv[v]) {
        addflow = min(addflow, graph[prevv[v]][preve[v]].cap);
      }
      f -= addflow;
      ret += addflow * potential[t];
      for(int v = t; v != s; v = prevv[v]) {
        edge &e = graph[prevv[v]][preve[v]];
        e.cap -= addflow;
        graph[v][e.rev].cap += addflow;
      }
    }
    return ret;
  }

  void output() {
    for(int i = 0; i < graph.size(); i++) {
      for(auto &e : graph[i]) {
        if(e.isrev) continue;
        auto &rev_e = graph[e.to][e.rev];
        cout << i << "->" << e.to << " (flow: " << rev_e.cap << "/" << rev_e.cap + e.cap << ")" << endl;
      }
    }
  }
};


int main() {
  using flow_t = int64;
  using cost_t = int64;

  int N, M;
  cin >> N >> M;
  vector< vector< int > > g(N);
  vector< int > X(M), Y(M), S(M);
  for(int i = 0; i < M; i++) {
    cin >> X[i] >> Y[i] >> S[i];
    g[X[i]].emplace_back(i);
  }
  auto dp = make_v< int >(N);
  for(int i = 0; i < N; i++) {
    for(auto &j : g[i]) chmax(dp[Y[j]], dp[i] + S[j]);
  }

  vector< edge< flow_t, cost_t > > es;
  vector< flow_t > D(N);
  for(int i = 0; i < M; i++) es.emplace_back(Y[i], X[i], 1, inf, -S[i]);
  es.emplace_back(0, N - 1, 0, inf, dp[N - 1]);
  cout << normalized_min_cost_flow< flow_t, cost_t, PrimalDual >(D, es) << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 3324
final_rank: 7

code_snippet: #include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
const ll inf = 1e14;

class min_cost_flow{
private:
    int N;
    struct edge{int to; ll cap,cost; int rev;};
    vector<vector<edge>> G;
    vector<ll> h,dist,prevv,preve;
public:
    min_cost_flow(int n){
        N = n;
        G = vector<vector<edge>>(N);
        h = dist = prevv = preve = vector<ll>(N,0);
    }
    void add_edge(int from,int to,ll cap,ll cost){
        G[from].push_back((edge){to,cap,cost,(int) G[to].size()});
        G[to].push_back((edge){from,0,-cost,(int) G[from].size()-1});
    }
    ll answer(int s,int t,ll f){
        ll res = 0;
        fill(h.begin(),h.end(),0);
        while(f>0){
            priority_queue<P,vector<P>,greater<P>> Q;
            fill(dist.begin(),dist.end(),inf);
            dist[s] = 0;
            Q.push(P(0,s));
            while(!Q.empty()){
                P p = Q.top(); Q.pop();
                int v = p.second;
                if(dist[v]<p.first) continue;
                for(int i=0;i<G[v].size();i++){
                    edge &e = G[v][i];
                    if(e.cap>0 && dist[e.to]>dist[v]+e.cost+h[v]-h[e.to]){
                        dist[e.to] = dist[v]+e.cost+h[v]-h[e.to];
                        prevv[e.to] = v;
                        preve[e.to] = i;
                        Q.push(P(dist[e.to],e.to));
                    }
                }
            }
            if(dist[t]==inf) return -1;
            for(int v=0;v<N;v++) h[v] += dist[v];
            ll d = f;
            for(int v=t;v!=s; v=prevv[v]){
                d = min(d,G[prevv[v]][preve[v]].cap);
            }
            f -= d;
            res += d*h[t];
            for(int v=t;v!=s;v=prevv[v]){
                edge &e = G[prevv[v]][preve[v]];
                e.cap -= d;
                G[v][e.rev].cap += d;
            }
        }
        return res;
    }
};

struct edge{
    ll s,t,d;
};

int main(){
    int N,M;
    cin >> N >> M;
    vector<vector<edge>> g(N);
    vector<edge> edges(M);
    for(int i=0;i<M;i++){
        int a,b,c;
        cin >> a >> b >> c;
        edges[i] = {a,b,c};
        g[a].push_back({a,b,c});
    }
    vector<ll> dp(N,0);
    for(int i=N-1;i>=0;i--){
        for(auto& e:g[i]) dp[i] = max(dp[i],dp[e.t]+e.d);
    }
    ll D = dp[0];
    min_cost_flow flow(N+2);
    vector<ll> b(N,0);
    flow.add_edge(0,N-1,inf,D);
    ll ans = 0;
    ll tinf = 10000;
    for(auto& e:edges){
        b[e.t] -= tinf;
        b[e.s] += tinf;
        ans += -e.d*tinf;
        flow.add_edge(e.s,e.t,tinf-1,e.d);
    }
    ll sum = 0;
    for(int i=0;i<N;i++){
        if(b[i]>0) flow.add_edge(N,i,b[i],0);
        if(b[i]<0) flow.add_edge(i,N+1,-b[i],0);
        sum += max(b[i],0LL);
    }
    cout << ans+flow.answer(N,N+1,sum) << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 3328
final_rank: 8

code_snippet: #include <bits/stdc++.h>

using namespace std;

using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using vi = vector<int>;
using vl = vector<ll>;

using _loop_int = int;
#define REP(i,n) for(_loop_int i=0; i<(_loop_int)(n); i++)
#define FOR(i,a,b) for(_loop_int i=(_loop_int)(a); i<(_loop_int)(b); i++)
#define FORR(i,a,b) for(_loop_int i=(_loop_int)(b)-1; i>=(_loop_int)(a); i--)

#define CHMIN(a,b) (a)=min((a),(b))
#define CHMAX(a,b) (a)=max((a),(b))
#define ALL(v) (v).begin(),(v).end()

#define DEBUG(x) cerr<<#x<<": "<<(x)<<endl
#define DEBUG_VEC(v) cerr<<#v<<": ";REP(__i,(v).size())cerr<<((v)[__i])<<", ";cerr<<endl

const ll MOD = 1000000007ll;

template<typename T>
struct MCF {
    using P = pair<T,int>;
    struct edge {
        int to; T cap; T cost; int rev;
        edge(int a, T b, T c, int d):to(a),cap(b),cost(c),rev(d){}
    };
    vector<vector<edge>> G;
    vector<T> h,dist;
    vector<int> prevv,preve;
    int V;
    MCF(int v):G(v),prevv(v,0),preve(v,0),V(v){}
    void add_edge(int from, int to, T cap, T cost){
        G[from].push_back(edge(to,cap,cost,G[to].size()));
        G[to].push_back(edge(from,0,-cost,G[from].size()-1));
    }
    T solve(int s, int t, T f, T COST_INF=(1<<30)){
        T res = 0;
        h.assign(V, 0);
        while(f > 0){
            priority_queue<P,vector<P>,greater<P>> Q;
            dist.assign(V, COST_INF);
            dist[s] = 0;
            Q.push(P(0,s));
            while(Q.size()){
                P p = Q.top(); Q.pop();
                int v = p.second;
                if(dist[v] < p.first)continue;
                REP(i,G[v].size()){
                    edge &e = G[v][i];
                    T d = dist[v] + e.cost + h[v] - h[e.to];
                    if(e.cap > 0 && dist[e.to] > d){
                        dist[e.to] = d;
                        prevv[e.to] = v;
                        preve[e.to] = i;
                        Q.push(P(dist[e.to], e.to));
                    }
                }
            }
            if(dist[t] == COST_INF){
                // return -1;
                break;
            }
            REP(v,V)h[v] += dist[v];
            T d = f;
            for(int v=t; v!=s; v=prevv[v]){
                d = min(d, G[prevv[v]][preve[v]].cap);
            }
            f -= d;
            res += d*h[t];
            for(int v=t; v!=s; v=prevv[v]){
                edge &e = G[prevv[v]][preve[v]];
                e.cap -= d;
                G[v][e.rev].cap += d;
            }
        }
        return res;
    }
};

template<typename T>
struct MCC {
    MCF<T> mcf;
    int V,source,sink;
    T sum;
    MCC(int v):V(v+2),mcf(v+2),source(v),sink(v+1),sum(0){}
    void add_edge(int from, int to, T lb, T ub, T cost){
        if(cost < 0){
            sum += cost * ub;
            mcf.add_edge(source,to,ub,0);
            mcf.add_edge(from,sink,ub,0);
            if(ub-lb > 0){
                mcf.add_edge(to,from,ub-lb,-cost);
            }
        }else{
            sum += cost * lb;
            if(lb > 0){
                mcf.add_edge(source,to,lb,0);
                mcf.add_edge(from,sink,lb,0);
            }
            if(ub-lb > 0){
                mcf.add_edge(from,to,ub-lb,cost);
            }
        }
    }
    T solve(T f, T COST_INF=(1<<30)){
        return sum + mcf.solve(source, sink, f, COST_INF);
    }
};

int n,m;
vector<pii> g[125];

int main(){
    scanf("%d%d",&n,&m);
    REP(i,m){
        int x,y,s;
        scanf("%d%d%d",&x,&y,&s);
        g[x].push_back(pii(y,s));
    }
    // calc max dist (DAG)
    vector<int> dist(n, 0);
    REP(i,n)for(pii P : g[i])CHMAX(dist[P.first], dist[i]+P.second);
    int x = dist[n-1];
    const ll INF = 1ll<<30;
    MCC<ll> mcc(n);
    const int start = 0;
    const int goal = n-1;
    // constraint: goal - start <= x
    // > goal - start <= x -> cost = 0
    // > goal - start >  x -> cost = INF
    mcc.add_edge(start, goal, 0, INF, x);
    REP(u,n)for(pii P : g[u]){
        int v = P.first;
        int s = P.second;
        // constraint: v - u >= s
        // > u - v <= -s -> cost = 1 * (u - v)
        // > u - v >  -s -> cost = INF
        mcc.add_edge(v, u, 1, INF, -s);
    }
    ll ans = mcc.solve(1ll<<60, 1ll<<60);
    printf("%lld\n",ans);
    return 0;
}
accuracy: 1
time_ms: 70
memory_kb: 3356
final_rank: 18

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}


template<typename TF,typename TC>
struct PrimalDual{
  struct edge{
    int to;
    TF cap;
    TC cost;
    int rev;
    edge(){}
    edge(int to,TF cap,TC cost,int rev):
      to(to),cap(cap),cost(cost),rev(rev){}
  };

  static const TC INF;
  vector<vector<edge>> G;
  vector<TC> h,dist;
  vector<int> prevv,preve;

  PrimalDual(){}
  PrimalDual(int n):G(n),h(n),dist(n),prevv(n),preve(n){}

  void add_edge(int u,int v,TF cap,TC cost){
    G[u].emplace_back(v,cap,cost,G[v].size());
    G[v].emplace_back(u,0,-cost,G[u].size()-1);
  }

  void dijkstra(int s){
    struct P{
      TC first;
      int second;
      P(TC first,int second):first(first),second(second){}
      bool operator<(const P&a) const{return a.first<first;}
    };
    priority_queue<P> que;
    fill(dist.begin(),dist.end(),INF);

    dist[s]=0;
    que.emplace(dist[s],s);
    while(!que.empty()){
      P p=que.top();que.pop();
      int v=p.second;
      if(dist[v]<p.first) continue;
      for(int i=0;i<(int)G[v].size();i++){
        edge &e=G[v][i];
        if(e.cap==0) continue;
        if(dist[v]+e.cost+h[v]-h[e.to]<dist[e.to]){
          dist[e.to]=dist[v]+e.cost+h[v]-h[e.to];
          prevv[e.to]=v;
          preve[e.to]=i;
          que.emplace(dist[e.to],e.to);
        }
      }
    }
  }

  TC flow(int s,int t,TF f,int &ok){
    TC res=0;
    fill(h.begin(),h.end(),0);
    while(f>0){
      dijkstra(s);
      if(dist[t]==INF){
        ok=0;
        return res;
      }

      for(int v=0;v<(int)h.size();v++)
        if(dist[v]<INF) h[v]=h[v]+dist[v];

      TF d=f;
      for(int v=t;v!=s;v=prevv[v])
        d=min(d,G[prevv[v]][preve[v]].cap);

      f-=d;
      res=res+h[t]*d;
      for(int v=t;v!=s;v=prevv[v]){
        edge &e=G[prevv[v]][preve[v]];
        e.cap-=d;
        G[v][e.rev].cap+=d;
      }
    }
    ok=1;
    return res;
  }
};
template<typename TF, typename TC>
const TC PrimalDual<TF, TC>::INF = numeric_limits<TC>::max()/2;


template<typename TF,typename TC>
struct NegativeEdge{
  PrimalDual<TF, TC> G;
  vector<TF> fs;
  TC sum;
  int S,T;
  NegativeEdge(){}
  NegativeEdge(int n):G(n+2),fs(n+2,0),sum(0),S(n),T(n+1){}

  void use_edge(int u,int v,TF cap,TC cost){
    fs[u]-=cap;
    fs[v]+=cap;
    sum=sum+cost*cap;
  }

  void add_edge(int u,int v,TF cap,TC cost){
    if(cost<TC(0)){
      use_edge(u,v,cap,cost);
      swap(u,v);
      cost=-cost;
    }
    G.add_edge(u,v,cap,cost);
  }

  TC flow(int &ok){
    TF f=0;
    for(int i=0;i<S;i++){
      if(fs[i]>0){
        f+=fs[i];
        G.add_edge(S,i,+fs[i],TC(0));
      }
      if(fs[i]<0){
        G.add_edge(i,T,-fs[i],TC(0));
      }
    }
    return sum+G.flow(S,T,f,ok);
  }

  TC flow(int ts,int tt,TF tf,int &ok){
    fs[ts]+=tf;
    fs[tt]-=tf;
    return flow(ok);
  }
};

//INSERT ABOVE HERE
signed main(){
  using P = pair<int, int>;
  using ll = long long;
  const ll INF = 1e9;

  int n,m;
  cin>>n>>m;
  vector< vector<P> > H(n);
  NegativeEdge<ll, ll> G(n);
  for(int i=0;i<m;i++){
    int x,y,s;
    cin>>x>>y>>s;
    H[x].emplace_back(y,s);
    G.add_edge(y,x,1,-s-INF);
    G.add_edge(y,x,INF,-s);
  }

  vector<int> dp(n,0);
  for(int i=0;i<n;i++)
    for(auto e:H[i])
      chmax(dp[e.first],dp[i]+e.second);
  G.add_edge(0,n-1,INF,dp[n-1]);

  int ok=0;
  cout<<INF*m+G.flow(ok)<<endl;
  assert(ok);
  return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3280
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}


template<typename TF,typename TC>
struct PrimalDual{
  struct edge{
    int to;
    TF cap;
    TC cost;
    int rev;
    edge(){}
    edge(int to,TF cap,TC cost,int rev):
      to(to),cap(cap),cost(cost),rev(rev){}
  };

  static const TC INF;
  vector<vector<edge>> G;
  vector<TC> h,dist;
  vector<int> prevv,preve;

  PrimalDual(){}
  PrimalDual(int n):G(n),h(n),dist(n),prevv(n),preve(n){}

  void add_edge(int u,int v,TF cap,TC cost){
    G[u].emplace_back(v,cap,cost,G[v].size());
    G[v].emplace_back(u,0,-cost,G[u].size()-1);
  }

  void dijkstra(int s){
    struct P{
      TC first;
      int second;
      P(TC first,int second):first(first),second(second){}
      bool operator<(const P&a) const{return a.first<first;}
    };
    priority_queue<P> que;
    fill(dist.begin(),dist.end(),INF);

    dist[s]=0;
    que.emplace(dist[s],s);
    while(!que.empty()){
      P p=que.top();que.pop();
      int v=p.second;
      if(dist[v]<p.first) continue;
      for(int i=0;i<(int)G[v].size();i++){
        edge &e=G[v][i];
        if(e.cap==0) continue;
        if(dist[v]+e.cost+h[v]-h[e.to]<dist[e.to]){
          dist[e.to]=dist[v]+e.cost+h[v]-h[e.to];
          prevv[e.to]=v;
          preve[e.to]=i;
          que.emplace(dist[e.to],e.to);
        }
      }
    }
  }

  TC flow(int s,int t,TF f,int &ok){
    TC res=0;
    fill(h.begin(),h.end(),0);
    while(f>0){
      dijkstra(s);
      if(dist[t]==INF){
        ok=0;
        return res;
      }

      for(int v=0;v<(int)h.size();v++)
        if(dist[v]<INF) h[v]=h[v]+dist[v];

      TF d=f;
      for(int v=t;v!=s;v=prevv[v])
        d=min(d,G[prevv[v]][preve[v]].cap);

      f-=d;
      res=res+h[t]*d;
      for(int v=t;v!=s;v=prevv[v]){
        edge &e=G[prevv[v]][preve[v]];
        e.cap-=d;
        G[v][e.rev].cap+=d;
      }
    }
    ok=1;
    return res;
  }
};
template<typename TF, typename TC>
const TC PrimalDual<TF, TC>::INF = numeric_limits<TC>::max()/2;


template<typename TF,typename TC>
struct NegativeEdge{
  PrimalDual<TF, TC> G;
  vector<TF> fs;
  TC sum;
  int S,T;
  NegativeEdge(){}
  NegativeEdge(int n):G(n+2),fs(n+2,0),sum(0),S(n),T(n+1){}

  void use_edge(int u,int v,TF cap,TC cost){
    fs[u]-=cap;
    fs[v]+=cap;
    sum=sum+cost*cap;
  }

  void add_edge(int u,int v,TF cap,TC cost){
    if(cost<TC(0)){
      use_edge(u,v,cap,cost);
      swap(u,v);
      cost=-cost;
    }
    G.add_edge(u,v,cap,cost);
  }

  TC flow(int &ok){
    TF f=0;
    for(int i=0;i<S;i++){
      if(fs[i]>0){
        f+=fs[i];
        G.add_edge(S,i,+fs[i],TC(0));
      }
      if(fs[i]<0){
        G.add_edge(i,T,-fs[i],TC(0));
      }
    }
    return sum+G.flow(S,T,f,ok);
  }

  TC flow(int ts,int tt,TF tf,int &ok){
    fs[ts]+=tf;
    fs[tt]-=tf;
    return flow(ok);
  }
};

//INSERT ABOVE HERE
signed main(){
  using P = pair<int, int>;
  using ll = long long;
  const ll INF = 1e9;

  int n,m;
  cin>>n>>m;
  vector< vector<P> > H(n);
  NegativeEdge<ll, ll> G(n);
  for(int i=0;i<m;i++){
    int x,y,s;
    cin>>x>>y>>s;
    H[x].emplace_back(y,s);
    G.add_edge(x,y,1,-s-INF);
    G.add_edge(x,y,INF,-s);
  }

  vector<int> dp(n,0);
  for(int i=0;i<n;i++)
    for(auto e:H[i])
      chmax(dp[e.first],dp[i]+e.second);
  G.add_edge(n-1,0,INF,dp[n-1]);

  int ok=0;
  cout<<INF*m+G.flow(ok)<<endl;
  assert(ok);
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3296
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef pair<int,P> P1;
typedef pair<P,P> P2;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-7
//#define INF 1000000000
#define mod 1000000007
#define fi first
#define sc second
#define rep(i,x) for(int i=0;i<x;i++)
#define repn(i,x) for(int i=1;i<=x;i++)
#define SORT(x) sort(x.begin(),x.end())
#define ERASE(x) x.erase(unique(x.begin(),x.end()),x.end())
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin())
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin())
#define int long long
ll D;

template< typename flow_t, typename cost_t >
struct PrimalDual {
  const cost_t INF;

  struct edge {
    int to;
    flow_t cap;
    cost_t cost;
    int rev;
    bool isrev;
  };
  vector< vector< edge > > graph;
  vector< cost_t > potential, min_cost;
  vector< int > prevv, preve;

  PrimalDual(int V) : graph(V), INF(1000000000LL) {}

  void add_edge(int from, int to, flow_t cap, cost_t cost) {
    graph[from].emplace_back((edge) {to, cap, cost, (int) graph[to].size(), false});
    graph[to].emplace_back((edge) {from, 0, -cost, (int) graph[from].size() - 1, true});
  }

  cost_t min_cost_flow(int s, int t, flow_t f) {
    int V = (int) graph.size();
    cost_t ret = 0;
    using Pi = pair< cost_t, int >;
    priority_queue< Pi, vector< Pi >, greater< Pi > > que;
    potential.assign(V, 0);
    preve.assign(V, -1);
    prevv.assign(V, -1);

    while(f > 0) {
      min_cost.assign(V, INF);
      que.emplace(0, s);
      min_cost[s] = 0;
      while(!que.empty()) {
        Pi p = que.top();
        que.pop();
        if(min_cost[p.second] < p.first) continue;
        for(int i = 0; i < graph[p.second].size(); i++) {
          edge &e = graph[p.second][i];
          cost_t nextCost = min_cost[p.second] + e.cost + potential[p.second] - potential[e.to];
          if(e.cap > 0 && min_cost[e.to] > nextCost) {
            min_cost[e.to] = nextCost;
            prevv[e.to] = p.second, preve[e.to] = i;
            que.emplace(min_cost[e.to], e.to);
          }
        }
      }
      if(min_cost[t] == INF) return -1;
      for(int v = 0; v < V; v++) potential[v] += min_cost[v];
      flow_t addflow = f;
      for(int v = t; v != s; v = prevv[v]) {
        addflow = min(addflow, graph[prevv[v]][preve[v]].cap);
      }
      f -= addflow;
      ret += addflow * potential[t];
      ret += addflow * D;
      for(int v = t; v != s; v = prevv[v]) {
        edge &e = graph[prevv[v]][preve[v]];
        e.cap -= addflow;
        graph[v][e.rev].cap += addflow;
      }
    }
    return ret;
  }

  void output() {
    for(int i = 0; i < graph.size(); i++) {
      for(auto &e : graph[i]) {
        if(e.isrev) continue;
        auto &rev_e = graph[e.to][e.rev];
        cout << i << "->" << e.to << " (flow: " << rev_e.cap << "/" << rev_e.cap + e.cap << ")" << endl;
      }
    }
  }
};

int n,m;
vector<P>edge[105];
int dp[105];

int calc(int v){
	if(dp[v] >= 0) return dp[v];
	dp[v] = 0;
	if(v == n-1) return dp[v];
	for(int i=0;i<edge[v].size();i++){
		dp[v] = max(dp[v],calc(edge[v][i].fi)+edge[v][i].sc);
	}
	return dp[v];
}

signed main(){
	cin>>n>>m;
	rep(i,m){
		int x,y,s; cin>>x>>y>>s;
		edge[x].pb(mp(y,s));
	}
	memset(dp,-1,sizeof(dp));
	D = calc(0);
	ll ans = 0;
	PrimalDual<int,int>g(n);
	rep(i,n){
		rep(j,edge[i].size()){
			int u = i,v = edge[i][j].fi,cs = edge[i][j].sc;
			ans += 200000-cs;
			g.add_edge(v,u,1,-200000);
			g.add_edge(v,u,1e9,-cs);
		}
	}
	ans += g.min_cost_flow(n-1,0,1e9);
	ll ans2 = 0;
	rep(i,n){
		rep(j,edge[i].size()){
			int u = i,v = edge[i][j].fi,cs = edge[i][j].sc;
			ans2 += g.potential[v]-g.potential[u]-cs; 
			assert(g.potential[v]-g.potential[u]-cs >= 0);
			edge[i][j].sc = g.potential[v]-g.potential[u];
		}
	}
	memset(dp,-1,sizeof(dp));
	ll DD = calc(0);
	assert(ans == ans2);
	assert(D == DD);
	cout << ans << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 3308
final_rank: 5