#include<cstdio> #include<set> #include<vector> #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) using namespace std; char c[200][201]; set<vector<unsigned char> > history; vector<int> graph[200]; int n, b, r; void move(vector<unsigned char> & miners) { set<unsigned char> S; for (unsigned char miner : miners) { for (int v : graph[miner]) { S.insert(v); } } vector<unsigned char> result(S.begin(), S.end()); miners.swap(result); } bool in_bases(vector<unsigned char> & miners) { return miners[miners.size() - 1] < b; } int main() { scanf("%d%d%d", &n , &b, &r); REP(i, n) { scanf("%s", c[i]); REP(j, n) { if (c[i][j] == '1') { graph[i].push_back(j); } } } vector<unsigned char> miners(r); REP(i, r) { int miner; scanf("%d", &miner); miners[i] = miner - 1; } int moves = 0; while (!in_bases(miners)) { history.insert(miners); move(miners); moves++; if (history.count(miners)) { moves = -1; break; } } printf("%d\n", moves); return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include<cstdio> #include<set> #include<vector> #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) using namespace std; char c[200][201]; set<vector<unsigned char> > history; vector<int> graph[200]; int n, b, r; void move(vector<unsigned char> & miners) { set<unsigned char> S; for (unsigned char miner : miners) { for (int v : graph[miner]) { S.insert(v); } } vector<unsigned char> result(S.begin(), S.end()); miners.swap(result); } bool in_bases(vector<unsigned char> & miners) { return miners[miners.size() - 1] < b; } int main() { scanf("%d%d%d", &n , &b, &r); REP(i, n) { scanf("%s", c[i]); REP(j, n) { if (c[i][j] == '1') { graph[i].push_back(j); } } } vector<unsigned char> miners(r); REP(i, r) { int miner; scanf("%d", &miner); miners[i] = miner - 1; } int moves = 0; while (!in_bases(miners)) { history.insert(miners); move(miners); moves++; if (history.count(miners)) { moves = -1; break; } } printf("%d\n", moves); return 0; } |