vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
        // Init
        VI ans;
        VVI adj(n);
        QI q;
        VI d(n, -1), pathTo(n);
        for(auto& pr: edges) {
            int u = pr.first, v = pr.second;
            adj[u].push_back(v);
            adj[v].push_back(u);
        }
        // Find one endpoint of longest path
        int start = 0;
        q.push(0);
        d[0] = 0;
        while(!q.empty()) {
            int u = q.front(); q.pop();
            start = u;
            
            for(int v: adj[u]) {
                if(d[v] == -1) {
                    d[v] = d[u] + 1;
                    q.push(v);
                }
            }
        }

        // Find longest path
        int maxd = 0, end = start;
        q = QI();
        fill(d.begin(), d.end(), -1);
        q.push(start);
        d[start] = 0;
        while(!q.empty()) {
            int u = q.front(); q.pop();
            maxd = d[u];
            end = u;

            for(int v: adj[u]) {
                if(d[v] == -1) {
                    pathTo[v] = u;
                    d[v] = d[u] + 1;
                    q.push(v);
                }
            }
        }

        // Find mid points
        int s = end;
        for(int i = 0; i < maxd / 2; i++) {
            s = pathTo[s];
        }
        ans.push_back(s);
        if(maxd & 1) {
            ans.push_back(pathTo[s]);
        }

        return ans;
    }
示例#2
0
int main(){
	int t, n, m;
	scanf("%d", &t);
	while(t--){
		scanf("%d%d", &n, &m);
		bool vis[m + 5] = {0};
		QI q;
		map<int, QI> myp;
		while(n--){
			char s[10];
			scanf("%s", s);
			if(!strcmp(s, "push")){
				int a, b;
				scanf("%d%d", &a, &b);
				if(!vis[b]){
					q.push(b);
					vis[b] = 1;
				}
				auto &x = myp[b];
				x.push(a);
			}
			if(!strcmp(s, "pop")){
				int tmp = q.front();
				auto &x = myp[tmp];
				printf("%d\n", x.front());
				x.pop();
				if(x.empty()){
					vis[tmp] = 0;
					q.pop();
				}
			}
		}
	}
}
示例#3
0
void bfs() {
	while(q.size() > 0) {
		int u = q.front();
		
		VI adj = g[u];
		
		for(int i = 0; i < adj.size(); ++i) {
			int v = adj[i];
			cf[v]++;
			cnt[v] = max(cnt[v], w[v] && !w[u] ? cnt[u] + 1 : cnt[u]);
			if(rf[v] == cf[v]) q.push(v);
		}
		
		q.pop();
	}
}
bool Graph::isReachable(int src, int dest) {
    if(src == dest)
        return true;
    bool visit[V];
    fill(visit, visit+V, false);
    QI q;
    q.push(src);
    LI::iterator iter;
    visit[src] = true;
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        iter = adj[u].begin();
        for(; iter != adj[u].end(); iter++) {
            if(*iter == dest)
                return true;
            if(!visit[*iter]) {
                visit[*iter] = 1;
                q.push(*iter);
            }
        }
    }
    return false;
}