首先,看到标签有拓扑排序,然后题面中提到任务间有依赖关系,所以必定首选拓扑排序。
因为要让副处理器处理次数尽量少,所以就要让主处理器处理次数尽量多。所以开两个队列,一个维护主处理器,另一个维护副处理器。先对主处理器拓扑排序,主处理器拓扑排序完判断维护副处理器的队列中是否还有元素,如果有,则将答案加 111,然后再对副处理器拓扑排序。
然后就 AC 了。
#include <bits/stdc++.h>
using namespace std;
int n,m,ans,a[100010],in[100010];
int tot,hd[100010],to[100010],nx[100010];
queue<int> mp,sp;
void add (int x,int y) {
to[++tot]=y;
nx[tot]=hd[x];
hd[x]=tot;
}
int main () {
cin>> n>> m;
for (int i=0;i<n;i++) cin>> a[i];
for (int i=1;i<=m;i++) {
int u,v;
cin>> u>> v;
add (v,u);
in[u]++;
}
for (int i=0;i<n;i++)
if (!in[i])
a[i]==0? mp.push (i): sp.push (i);
while (!mp.empty ()||!sp.empty ()) {
while (!mp.empty ()) {
int u=mp.front ();
mp.pop ();
for (int i=hd[u];i;i=nx[i]) {
int v=to[i];
if (!(--in[v]))
a[v]==0? mp.push (v): sp.push (v);
}
}
if (!sp.empty ()) ans++;
while (!sp.empty ()) {
int u=sp.front ();
sp.pop ();
for (int i=hd[u];i;i=nx[i]) {
int v=to[i];
if (!(--in[v]))
a[v]==0? mp.push (v): sp.push (v);
}
}
}
cout<< ans;
return 0;
}