Reward (圖論+拓撲排序)
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.
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.
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<cstdio>
#include<queue>
#include<vector>
using namespace std;
const int maxn=11000;
int n,m,ans[maxn],r[maxn];
vector <vector<int> >v;
void input(){
v.clear();
v.resize(n+1);
for(int i=0;i<=n;i++)
{
ans[i]=-1;
r[i]=0;
}
int a,b;
while(m-->0)
{
scanf("%d%d",&a,&b);
v[b].push_back(a);
r[a]++;
}
}
void solve(){
queue <int> q;
for(int i=1;i<=n;i++)
{
if(r[i]==0)q.push(i);//將沒有依賴頂點的結點入隊
}
int tmp=888;
while(!q.empty())
{
int qsize=q.size();
while(qsize--)
{
int s=q.front();
q.pop();
ans[s]=tmp;
for(int i=0;i<v[s].size();i++)
{
int d=v[s][i];
r[d]--;
if(r[d]==0)q.push(d);
}
}
tmp++;
}
int sum=0;
for(int i=1;i<=n;i++)
{
if(ans[i]>0)sum+=ans[i];
else{
sum=-1;
break;
}
}
cout<<sum<<endl;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF)
{
input();
solve();
}
return 0;
}
相關文章
- 圖論——拓撲排序圖論排序
- 演算法-圖論-拓撲排序演算法圖論排序
- 【圖論】拓撲排序+優先佇列圖論排序佇列
- 拓撲排序排序
- 有向圖的拓撲排序——DFS排序
- 拓撲排序,YYDS排序
- 拓撲排序模板排序
- 圖解拓撲排序+程式碼實現圖解排序
- 拓撲排序小結排序
- 筆記:拓撲排序筆記排序
- 圖的拓撲排序詳解與實現排序
- 圖(3)--拓撲排序與關鍵路徑排序
- 拓撲排序 (BFS )DAG (有向無環圖)排序
- 拓撲排序 - Topological Sort排序
- 拓撲排序核心程式碼排序
- HDU 4857 逃生(拓撲排序)排序
- 【筆記/模板】拓撲排序筆記排序
- AOV網與拓撲排序排序
- DFS實現拓撲排序排序
- 演算法資料結構 | 圖論基礎演算法——拓撲排序演算法資料結構圖論排序
- 拓撲排序就這麼回事排序
- HDU4857逃生(拓撲排序)排序
- 紙上談兵: 拓撲排序排序
- poj 1094 拓撲排序排序
- poj1094 拓撲排序排序
- 網路拓撲圖:網路拓撲圖介紹及線上製作
- POJ 3249-Test for Job(拓撲排序&&DP)排序
- HDU 5438 Ponds (拓撲排序應用+DFS)排序
- CF 274D Lovely Matrix(拓撲排序)排序
- HDU 4857-逃生(反向拓撲排序-按條件排序)排序
- hdu 1811 並查集+拓撲排序並查集排序
- (set+拓撲排序) CF1572A Book排序
- 團隊拓撲快速參考圖
- vue 實現動態拓撲圖Vue
- HT For Web 拓撲圖背景設定Web
- 網站拓撲圖(來自qq)網站
- VOL.2 拓撲排序與關鍵路徑排序
- POJ1094[有向環 拓撲排序]排序