标签:example main 访问 cannot and namespace cto iter long
4 3
3 1 2 3
2 4 2
3 3 4 1
1 4 2 3
Here, Farmer John has four cows and should milk cow 1 before cow 2 and cow 2 before cow 3 (the first observation), cow 4 before cow 2 (the second observation), and cow 3 before cow 4 and cow 4 before cow 1 (the third observation). The first two observations can be satisfied simultaneously, but Farmer John cannot meet all of these criteria at once, as to do so would require that cow 1 come before cow 3 and cow 3 before cow 1.
This means there are two possible orderings: 1 4 2 3 and 4 1 2 3, the first being lexicographically smaller.
#include <bits/stdc++.h> #define maxn 100005 using namespace std; typedef long long ll; int a[maxn]; int ans[maxn]; vector<int> v[maxn/2]; struct edge { int u,v,next; }edge[maxn*2]; int head[maxn]; int cnt=0; int ind[maxn]; void addedge(int u,int v) { ind[v]++; edge[cnt].u=u; edge[cnt].v=v; edge[cnt].next=head[u]; head[u]=cnt++; } int n; bool topsort() { priority_queue<int,vector<int>,greater<int> >q; int tot=-1,i; for(i=1;i<=n;i++) { if(ind[i]==0) q.push(i); } while(!q.empty()) { int u=q.top(); ans[++tot]=u; q.pop(); for(i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].v; ind[v]--; if(ind[v]==0) q.push(v); } } if(tot==n-1) return true; else return false; } using namespace std; int main() { int m,i,k,j; scanf("%d%d",&n,&m); for(i=0;i<m;i++) { scanf("%d",&k); for(j=1;j<=k;j++) { int u; scanf("%d",&u); v[i].push_back(u); } } int l=0,r=m-1; int mm=0; while(l<=r) { int mid=(l+r)>>1; cnt=0; memset(head,-1,sizeof(head)); memset(edge,0,sizeof(edge)); memset(ind,0,sizeof(ind)); for(i=0;i<=mid;i++) { for(j=0;j<v[i].size()-1;j++) { addedge(v[i][j],v[i][j+1]); } } if(topsort()) { l=mid+1; mm=max(mm,mid); } else { r=mid-1; } } memset(head,-1,sizeof(head)); memset(edge,0,sizeof(edge)); memset(ind,0,sizeof(ind)); cnt=0; for(i=0;i<=mm;i++) { for(j=0;j<v[i].size()-1;j++) { addedge(v[i][j],v[i][j+1]); } } topsort(); for(i=0;i<n-1;i++) { printf("%d ",ans[i]); } cout<<ans[i]<<endl; return 0; }
6348: Milking Order(二分答案+拓扑排序)
标签:example main 访问 cannot and namespace cto iter long
原文地址:https://www.cnblogs.com/zyf3855923/p/9351710.html