P2999 [USACO10NOV]Chocolate Milk S 题解

Pre-Knowledge --> Topological Sort

Why use topological sort for this question? According to the meaning of the question, the flow of each order of milk has a sequence, and the sequence cannot be changed.

The focus is on the application of the in-degree, out-degree, and queue of this question.

ideas

Milking machine: the in-degree is 0, and it can enter the queue at the earliest (because it is not limited by the order);

Mixer: The mixer should be placed at the point where each milk flow will pass, then the milk flow at this point = the total milk flow;

while Enqueue and dequeue operation: when the out-degree of the head of the queue is 1, you can enter the queue after the operation of his "child nodes" recorded before;

Answer statistics: When the milking machines are added to the team, the total milk volume is counted, the milk volume of each milking machine is 1, and tot is used for statistics. Finally, compare whether the milk flow at this point is equal to the total milk volume. If they are equal, then Record.


Code

#include<bits/stdc++.h>
using namespace std; 

const int maxn = 100010;
int n;
int to[maxn], ans[maxn];
int rd[maxn], cd[maxn];
int liu[maxn], ji[maxn];//挤奶器 
int tot;

queue <int> q;

int main()
{
    
    
	scanf ("%d", &n);
	for (int i = 1; i < n; i++)
	{
    
    
		int a, b;
		scanf ("%d %d", &a, &b);
		to[a] = b;
		cd[a]++;
		rd[b]++;
	}
	
	for (int i = 1; i <= n; i++)//寻找挤奶器 
	{
    
    
		if (!rd[i])
		{
    
    
			liu[i] = 1;
			tot += 1;
			q.push (i);
			ji[i] = 1;
		}
	}
	
	while (!q.empty())
	{
    
    
		int x = q.front ();
		q.pop ();
		if (cd[x] > 1) continue;
		//拓扑
		liu[to[x]] += liu[x];
		rd[to[x]] --;
		if (!rd[to[x]]) q.push (to[x]); 
	}
	
	int tmp = 1;
	for (int i = 1; i <= n; i++)
	{
    
    
		if (ji[i]) continue;//挤奶器
		if (tot == liu[i]) 
		{
    
    
			ans[tmp] = i;
			tmp ++;
		}
	}
	for (int i = 1; i < tmp; i++) printf ("%d\n", ans[i]);
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324153510&siteId=291194637