2330: [SCOI2011]糖果
Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 5225 Solved: 1677
[ Submit][ Status][ Discuss]
Description
幼儿园里有N个小朋友,lxhgww老师现在想要给这些小朋友们分配糖果,要求每个小朋友都要分到糖果。但是小朋友们也有嫉妒心,总是会提出一些要求,比如小明不希望小红分到的糖果比他的多,于是在分配糖果的时候,lxhgww需要满足小朋友们的K个要求。幼儿园的糖果总是有限的,lxhgww想知道他至少需要准备多少个糖果,才能使得每个小朋友都能够分到糖果,并且满足小朋友们所有的要求。
Input
输入的第一行是两个整数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个小朋友分到的糖果;
Output
输出一行,表示lxhgww老师至少需要准备的糖果数,如果不能满足小朋友们的所有要求,就输出-1。
Sample Input
5 7
1 1 2
2 3 2
4 4 1
3 4 5
5 4 5
2 3 5
4 5 1
1 1 2
2 3 2
4 4 1
3 4 5
5 4 5
2 3 5
4 5 1
Sample Output
11
HINT
【数据范围】
对于30%的数据,保证 N<=100
对于100%的数据,保证 N<=100000
对于所有的数据,保证 K<=100000,1<=X<=5,1<=A, B<=N
Source
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<bitset>
#include<ext/pb_ds/priority_queue.hpp>
using namespace std;
const int maxn = 1E5 + 10;
typedef long long LL;
struct E{
int to,w; E(){}
E(int to,int w): to(to),w(w){}
};
int n,k,dis[maxn];
bool vis[maxn];
vector <E> v[maxn];
bool SPFA(int x)
{
for (int i = 0; i < v[x].size(); i++)
{
E e = v[x][i];
if (dis[e.to] < dis[x] + e.w)
{
dis[e.to] = dis[x] + e.w;
if (vis[e.to]) return 0;
vis[e.to] = 1;
bool flag = SPFA(e.to);
if (!flag) return 0;
}
}
vis[x] = 0; return 1;
}
int main()
{
#ifdef DMC
freopen("DMC.txt","r",stdin);
#endif
cin >> n >> k;
while (k--)
{
int typ,x,y; scanf("%d%d%d",&typ,&x,&y);
if (typ == 1)
{
v[x].push_back(E(y,0));
v[y].push_back(E(x,0));
}
else if (typ == 2) v[x].push_back(E(y,1));
else if (typ == 3) v[y].push_back(E(x,0));
else if (typ == 4) v[y].push_back(E(x,1));
else v[x].push_back(E(y,0));
}
for (int i = 1; i <= n; i++) v[0].push_back(E(i,1));
vis[0] = 1;
if (!SPFA(0)) {cout << -1; return 0;}
LL Ans = 0;
for (int i = 1; i <= n; i++) Ans += 1LL*dis[i];
cout << Ans;
return 0;
}