2436. 「SCOI2011」糖果
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
/*
https://ac.nowcoder.com/acm/contest/961/C
https://loj.ac/p/2436
幼儿园里有N个小朋友,lxhgww老师现在想要给这些小朋友们分配糖果,要求每个小朋友都要分到糖果。
但是小朋友们也有嫉妒心,总是会提出一些要求,比如小明不希望小红分到的糖果比他的多,于是在分配糖果的时候,
lxhgww需要满足小朋友们的K个要求。
幼儿园的糖果总是有限的,lxhgww想知道他至少需要准备多少个糖果,才能使得每个小朋友都能够分到糖果,并且满足小朋友们所有的要求。
输入描述:
输入的第一行是两个整数N,K。
接下来K行,表示这些点需要满足的关系,每行3个数字,x,A,B。
如果X=1.表示第A个小朋友分到的糖果必须和第B个小朋友分到的糖果一样多。
如果X=2,表示第A个小朋友分到的糖果必须少于第B个小朋友分到的糖果。
如果X=3,表示第A个小朋友分到的糖果必须不少于第B个小朋友分到的糖果。
如果X=4,表示第A个小朋友分到的糖果必须多于第B个小朋友分到的糖果。
如果X=5,表示第A个小朋友分到的糖果必须不多于第B个小朋友分到的糖果。
输出描述:
输出一行,表示lxhgww老师至少需要准备的糖果数,如果不能满足小朋友们的所有要求,就输出-1。
5 7
1 1 2
2 3 2
4 4 1
3 4 5
5 4 5
2 3 5
4 5 1
11
4 7
1 3 2
2 2 4
5 1 3
3 4 2
3 2 3
4 3 1
5 1 4
-1
30%的数据,保证N<100。
100%的数据,保证N<100000,K≤100000,1≤X≤5,1≤A,B≤N。
*/
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef long long LL;
const int N = 100010, M = 300010;
int n, m;
int h[N], w[M], e[M], ne[M], idx;
int dist[N], cnt[N];
int q[N];
bool st[N];
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
bool spfa() {
int hh = 0, tt = -1;
//使用队列会超时 而且数组队列会越界 ,切记!! 调试了三小时
//使用堆栈 快速查找环 非常规手段
st[0] = true;
q[++tt] = 0;
dist[0] = 0;
while (hh<=tt) {
auto t = q[tt--];
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] < dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n+1)
return true;
if (!st[j])
{
q[++tt] = j;
st[j] = true;
}
}
}
}
return false;
}
int main() {
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 1; i <= n; i++) add(0, i, 1);
//最小值 要求最长路
while (m--) {
int x, a, b;
cin >> x >> a >> b;
if (x == 1) { add(a, b, 0); add(b, a, 0); }
if (x == 2) add(a, b, 1); //a<b a<=b-1 b>=a+1
if (x == 3) add(b, a, 0); //a>=b
if (x == 4) add(b, a, 1); //a >b a>=b+1
if (x == 5) add(a, b, 0); //a<=b b>=a
}
if (spfa()) {
cout << -1 << endl;
}
else {
LL res = 0;
for (int i = 1; i <= n; i++) res += dist[i];
cout << res << endl;
}
return 0;
}
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力

