Reward
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description
Dandelion's uncle is a boss of a factory. As the spring festival is coming , he wants to distribute rewards to his workers. Now he has a trouble about how to distribute the rewards.
The workers will compare their rewards ,and some one may have demands of the distributing of rewards ,just like a's reward should more than b's.Dandelion's unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every work's reward will be at least 888 , because it's a lucky number.
The workers will compare their rewards ,and some one may have demands of the distributing of rewards ,just like a's reward should more than b's.Dandelion's unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every work's reward will be at least 888 , because it's a lucky number.
Input
One line with two integers n and m ,stands for the number of works and the number of demands .(n<=10000,m<=20000)
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.
Output
For every case ,print the least money dandelion 's uncle needs to distribute .If it's impossible to fulfill all the works' demands ,print -1.
Sample Input
2 1 1 2 2 2 1 2 2 1
Sample Output
1777 -1
关键是要反向建图 然后用一个数组去记录一下每个点的层次
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <queue> #include <vector> #include <iomanip> #include <math.h> #include <map> using namespace std; #define FIN freopen("input.txt","r",stdin); #define FOUT freopen("output.txt","w",stdout); #define INF 0x3f3f3f3f #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 typedef long long LL; const int MAXN=1e5+5; struct Edge{ int v,nxt; }E[MAXN*2]; int Head[MAXN],erear; int IN[MAXN],P[MAXN]; int n,m,sz; int dis[MAXN]; //记录层次 void edge_init(){ erear=0; memset(Head,-1,sizeof(Head)); memset(IN,0,sizeof(IN)); memset(dis,0,sizeof(dis)); } void edge_add(int u,int v){ E[erear].v=v; E[erear].nxt=Head[u]; Head[u]=erear++; } int main() { //FIN while(~scanf("%d%d",&n,&m)) { edge_init(); for(int i=1;i<=m;i++){ int u,v; scanf("%d%d",&u,&v); edge_add(v,u); //反向建图 IN[u]++; } sz=0; queue<int>Q; for(int i=1;i<=n;i++){ if(!IN[i]){ Q.push(i); dis[i]=0; } } bool sign=0; while(!Q.empty()){ if(Q.size()>=2) sign++; int u=Q.front(); Q.pop(); P[sz++]=u; for(int i=Head[u];~i;i=E[i].nxt){ int v=E[i].v; dis[v]=dis[v]>(dis[u]+1)?dis[v]:(dis[u]+1); IN[v]--; if(!IN[v]) Q.push(v); } } if(sz!=n){ printf("-1 "); continue; } int ans=0; for(int i=1;i<=sz;i++){ ans+=dis[i]; } ans+=sz*888; printf("%d ",ans); } return 0; }