yukicoder no.30 たこやき工場

問題文
http://yukicoder.me/problems/a14e51c14f78a730

解法
DFS + メモ化再帰(=貰うDP)

コメントアウトはBFSでやろうとしてる。最短路をメモしないのでTLEする。

#include <bits/stdc++.h>

using namespace std;

#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)

#define INF (1<<29)

struct Edge
{
  int dst;
  int cost;
  Edge(int d, int c) : dst(d), cost(c) {}
};

vector<Edge> G[110];

typedef pair<int, int> Pii;

int N, M;
/*
// グラフを逆順にしてBFSするTLE解
vector<int> get(int st)
{
  vector<int> ans(N-1);
  
  queue<Pii> Q;
  Q.push(Pii(st, 1));
  while(!Q.empty()) {
    int pos = Q.front().first;
    int cost = Q.front().second; Q.pop();
    ans[pos] += cost;
    rep(i, G[pos].size()) {
      Q.push(Pii(G[pos][i].dst, G[pos][i].cost*cost));
    }
  }
  
  return ans;
}
*/

int ans[110];

int get(int pos)
{
  int& res = ans[pos];
  if(res != -1) return res;
  if(pos == N-1) return res = 1;
  
  res = 0;
  rep(i, G[pos].size()) {
    res += get(G[pos][i].dst) * G[pos][i].cost;
  }
  
  return res;
}

int main() {
  
  cin >> N >> M;
  
  bool isntLast[110] = {};
  rep(i, M) {
    int p, q, r;
    cin >> p >> q >> r; p --, r --;
    G[p].push_back(Edge(r, q));
    isntLast[r] = 1;
  }
  
  memset(ans, -1, sizeof ans);
  rep(i, N-1) {
    if(isntLast[i]) cout << 0 << endl;
    else cout << get(i) << endl;
  }
  
  return 0;
}