The kindergarten teacher sends candy to the friends. There are five requirements: Ask the teacher how many sweets should be prepared at least. If not, output-1.
Idea: bare-earth difference constraint system, but positive side addition will T, need to reverse side addition.
Code:
#include <queue>#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define MAX 400010using namespace std;int points,asks;int head[MAX],total;int next[MAX],aim[MAX],length[MAX];int f[MAX],showed_time[MAX];bool v[MAX];inline void Add(int x,int y,int len){next[++total] = head[x];aim[total] = y;length[total] = len;head[x] = total;}bool SPFA(){static queue<int> q;while(!q.empty())q.pop();q.push(0);memset(f,0xef,sizeof(f));f[0] = 0;while(!q.empty()) {int x = q.front(); q.pop();v[x] = false;for(int i = head[x]; i; i = next[i])if(f[aim[i]] < f[x] + length[i]) {f[aim[i]] = f[x] + length[i];if(!v[aim[i]]) {v[aim[i]] = true;q.push(aim[i]);showed_time[aim[i]] = showed_time[x] + 1;if(showed_time[aim[i]] > points + 1)return false;}}}return true;}int main(){cin >> points >> asks;for(int i = points; i; --i)Add(0,i,1);for(int flag,x,y,i = 1; i <= asks; ++i) {scanf("%d%d%d",&flag,&x,&y);if(flag == 1)Add(x,y,0),Add(y,x,0);if(flag == 2)Add(x,y,1);if(flag == 3)Add(y,x,0);if(flag == 4)Add(y,x,1);if(flag == 5)Add(x,y,0);}if(!SPFA()) {puts("-1");return 0;}long long ans = 0;for(int i = 1; i <= points; ++i)ans += f[i];cout << ans << endl;return 0;}
Bzoj 2330 scoi 2011 candy difference constraint system