天の川の星は広大ですが、最も明るい星にのみ焦点を当てています。
星の明るさを表すのに正の整数を使用します。値が大きいほど、星は明るくなります。星の最も暗い明るさは1です。
今私たちが心配しているN個の星について、Mと明るさの相対的な関係が決定されました。
あなたの仕事は、少なくともN個の星の輝度値の合計がどれだけ大きいかを見つけることです。
入力フォーマット
最初の行は2つの整数NとMを与えます。
M行の後、各行の3つの整数T、A、Bは、1組の星(A、B)間の明るさの関係を表します。星の番号は1から始まります。
T = 1の場合、AとBの明るさは等しくなります。
T = 2の場合、Aの輝度がBの輝度よりも低いことを意味します。
T = 3の場合、Aの輝度がBの輝度以上であることを意味します。
T = 4の場合、Aの輝度がBの輝度よりも大きいことを意味します。
T = 5の場合、Aの明るさがBの明るさより大きくないことを意味します。
出力フォーマット
結果を示す整数を出力します。
解がない場合は-1を出力します。
データ範囲
N≤100000、M≤100000N≤100000、M≤100000
入力サンプル:
5 7
1 1 2
2 3 2
4 4 1
3 4 5
5 4 5
2 3 5
4 5 1
出力例:
11
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010, M = 600010;
typedef long long LL;
int n, m;
int h[N], hs[N], e[M], w[M], ne[M], idx;
int dfn[N], low[N], timestamp;
int stk[N], top;
bool in_stk[N];
int id[N], scc_cnt, Size[N];
int dist[N];
void add(int h[], int a, int b, int c){
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
void tarjan(int u){
dfn[u] = low[u] = ++timestamp;
stk[++ top] = u, in_stk[u] = true;
for (int i = h[u]; ~i; i = ne[i]){
int j = e[i];
if (!dfn[j]){
tarjan(j);
low[u] = min(low[u], low[j]);
}
else if (in_stk[j]) low[u] = min(low[u], dfn[j]);
}
if (dfn[u] == low[u]){
++ scc_cnt;
int y;
do{
y = stk[top --];
in_stk[y] = false;
id[y] = scc_cnt;
Size[scc_cnt] ++;
}while(y != u);
}
}
int main(){
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
memset(hs, -1, sizeof hs);
for (int i = 1; i <= n; i ++) add(h, 0, i, 1);
while(m --){
int t, a, b;
scanf("%d%d%d", &t, &a, &b);
if (t == 1) add(h, a, b, 0), add(h, b, a, 0);
else if (t == 2) add(h, a, b, 1);
else if (t == 3) add(h, b, a, 0);
else if (t == 4) add(h, b, a, 1);
else add(h, a, b, 0);
}
tarjan(0);
bool success = true;
for (int i = 0; i <= n; i ++){
for (int j = h[i]; ~j; j = ne[j]){
int k = e[j];
int a = id[i], b = id[k];
if (a == b){
if (w[j] > 0){
success = false;
break;
}
}
else add(hs, a, b, w[j]);
}
if (!success) break;
}
if (!success) puts("-1");
else{
for (int i = scc_cnt; i; i --){
for (int j = hs[i]; ~j; j = ne[j]){
int k = e[j];
dist[k] = max(dist[k], dist[i] + w[j]);
}
}
LL res = 0;
for (int i = 1; i <= scc_cnt; i ++) res += (LL)dist[i] * Size[i];
cout << res << endl;
}
return 0;
}