#include #include using namespace std; typedef long long ll; template struct Edge { int to; T cost; }; template struct WeightedGraph { int n; std::vector>> g; WeightedGraph(){} WeightedGraph(int n) : n(n){ g.resize(n); } void add_edge(int from, int to, T cost){ g[from].push_back((Edge){to, cost}); } }; template std::vector dijkstra(WeightedGraph &g, int s){ int n = g.n; std::vector d(n); fill(d.begin(), d.end(), -2); std::priority_queue, std::vector>, std::greater>> que; d[s] = 0; que.push(std::pair(0, s)); while(que.size()){ std::pair p = que.top(); que.pop(); int u = p.second; if(d[u] < p.first) continue; for(Edge &e : g.g[u]){ int v = e.to; if(d[v] == -2 || d[v] > d[u] + e.cost){ d[v] = d[u] + e.cost; que.push(std::pair(d[v], v)); } } } return d; } int main() { int n, m; cin >> n >> m; int k[100005]; ll c[100005]; vector s[100005]; int l = 0; for(int i = 0; i < m; i++){ cin >> k[i] >> c[i]; l += k[i]; s[i].resize(k[i]); for(int j = 0; j < k[i]; j++) cin >> s[i][j]; } WeightedGraph g(l + m * 2 + 2); int id = m * 2; for(int i = 0; i < m; i++){ for(int j = 0; j < k[i]; j++){ g.add_edge(id, i * 2, (s[i][j] + 1) / 2 * 2 + c[i]); g.add_edge(i * 2, id, (s[i][j] + 1) / 2 * 2 + c[i]); if(s[i][j] % 2){ g.add_edge(id, i * 2 + 1, s[i][j] + c[i]); g.add_edge(i * 2 + 1, id, s[i][j] + c[i]); } if(s[i][j] == 1) g.add_edge(l + m * 2, id, 0); if(s[i][j] == n) g.add_edge(id, l + m * 2 + 1, 0); id++; } } vector d = dijkstra(g, l + m * 2); cout << d[l + m * 2 + 1] / 2 << endl; }