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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| #include <cstdio> #include <algorithm> #include <cstring> #include <queue>
using namespace std;
const int MAXM = 200010; const int MAXN = 100010;
template<typename T> T read() { T result = 0;int f = 1;char c = getchar(); while(c > '9' || c < '0') {if(c == '-') f *= -1;c = getchar();} while(c <= '9' && c >= '0') {result = result * 10 + c - '0';c = getchar();} return result * f; }
struct Graph { struct Edge { int next,to,weight; }; Edge edges[MAXM]; int tot,heads[MAXN];
Graph() : tot(0) { memset(heads,-1,sizeof(heads)); }
void addEdge(int u,int v,int w) { edges[tot].next = heads[u]; edges[tot].to = v; edges[tot].weight = w; heads[u] = tot++; } } graph;
int N,K,dis[MAXN],cnt[MAXN]; bool visit[MAXN];
bool spfa() { queue<int> que; for(int i = 1;i <= N;i++) { dis[i] = 1; visit[i] = true; que.push(i); } while(!que.empty()) { int now = que.front(); que.pop(); visit[now] = false; for(int i = graph.heads[now];i != -1;i = graph.edges[i].next) { Graph::Edge &tmpEdge = graph.edges[i]; if(dis[tmpEdge.to] >= dis[now] + tmpEdge.weight) continue; dis[tmpEdge.to] = dis[now] + tmpEdge.weight; if(!visit[tmpEdge.to]) { visit[tmpEdge.to] = true; que.push(tmpEdge.to); cnt[tmpEdge.to]++; if(cnt[tmpEdge.to] > N) { return false; } } } } return true; }
int main() { N = read<int>(); K = read<int>(); while(K--) { int opt = read<int>(),A = read<int>(),B = read<int>(); switch(opt) { case 1: { graph.addEdge(B,A,0); graph.addEdge(A,B,0); break; } case 2: { graph.addEdge(A,B,1); break; } case 3: { graph.addEdge(B,A,0); break; } case 4: { graph.addEdge(B,A,1); break; } case 5: { graph.addEdge(A,B,0); break; } } } bool result = spfa(); if(!result) { printf("-1\n"); }else { long long result = 0; for(int i = 1;i <= N;i++) { result += dis[i]; } printf("%lld\n",result); } return 0; }
|