比赛 |
4043级2023省选模拟赛2 |
评测结果 |
AAAAAAAAAA |
题目名称 |
糖果 |
最终得分 |
100 |
用户昵称 |
yuan |
运行时间 |
0.014 s |
代码语言 |
C++ |
内存使用 |
4.47 MiB |
提交时间 |
2023-03-22 20:46:47 |
显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int read()
{
int res = 0, w = 1;
char c = getchar();
while (!isdigit(c) && c != '-') c = getchar();
if (c == '-') c = getchar(), w = -1;
while (isdigit(c))
res = (res << 1) + (res << 3) + c - '0', c = getchar();
return res * w;
}
const int N = 200000 + 10;
struct Edge
{
int u, v, w, nxt;
} E[N << 1];
int head[N], tot = 0;
void addedge(int u, int v, int w)
{
E[++tot] = (Edge) { u, v, w, head[u] };
head[u] = tot;
}
int n, m, dis[N], inq[N], cnt[N];
queue<int> q;
bool spfa()
{
for (int i = 1; i <= n; i++)
{
inq[i] = dis[i] = 1;
q.push(i);
}
while (q.size())
{
int u = q.front(); q.pop();
inq[u] = 0;
for (int i = head[u]; i; i = E[i].nxt)
{
int v = E[i].v;
if (dis[v] < dis[u] + E[i].w)
{//最长路求最小值,构造>=不等式组
dis[v] = dis[u] + E[i].w;
if (++cnt[v] == n) return 0;//负环
if (!inq[v])
{
inq[v] = 1; q.push(v);
}
}
}
}
return 1;
}
int main()
{
freopen ("tangguo.in","r",stdin);
freopen ("tangguo.out","w",stdout);
n = read(), m = read();
for (int i = 1; i <= m; i++)
{
int op = read(), u = read(), v = read();
if (u == v && !(op & 1))
{
puts("-1"); return 0;
}
if (op == 1)
{//u==v
addedge(u, v, 0);//v>=u , v-u>=0
addedge(v, u, 0);//u>=v , u-v>=0
}
if (op == 2)//v>u , v>=u+1 , v-u>=1
addedge(u, v, 1);
if (op == 3)//u>=v , u-v>=0
addedge(v, u, 0);
if (op == 4)//u>v , u>=v+1 , u-v>=1
addedge(v, u, 1);
if (op == 5)//v>=u , v-u>=0
addedge(u, v, 0);
}
if(!spfa())
{
puts("-1"); return 0;
}
ll ans = 0;
for (int i = 1; i <= n; i++) ans += dis[i];//累加满足条件时每个人的最小值
cout << ans << endl;
return 0;
}