zoukankan      html  css  js  c++  java
  • 发糖果(拓扑排序模板)

    发糖果

    Code

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <cstdlib>
    #include <algorithm>
    #include <stack>
    using namespace std;
    const int N = 1e5 + 3;
    int n, m, buy[N], in[N];
    long long sum;
    struct edge {
    	int to, next;
    }e[N << 1];
    int head[N], cnt;
    stack <int> s;
    void add(int u,int v)
    {
    	e[++cnt].next = head[u];
    	e[cnt].to = v;
    	head[u] = cnt;
    }
    int main()
    {
    	cin >> n >> m;
    	for(int i = 1; i <= m; i++) {
    		int u, v;
    		cin >> u >> v;
    		add(v, u);
    		in[u]++;
    	}
    	cnt = 0;
    	for(int i = 1; i <= n; i++) {
    		if(in[i] == 0) {
    			s.push(i);
    			buy[i] = 1;
    		}
    	}
    	while(!s.empty()) {
    		int u = s.top();
    		s.pop();
    		cnt++;
    		for(int i = head[u]; i; i = e[i].next) {
    			int v = e[i].to;
    			in[v]--;
    			if(in[v] == 0) {
    				s.push(v);	
    			}
    			buy[v] = max(buy[v], buy[u] + 1);
    		}
    	}
    	if(cnt != n) {
    		cout << -1 << endl;
    	} else {
    		for(int i = 1; i <= n; i++) {
    			sum += buy[i];
    		}
    		cout << sum << endl;
    	}
    	return 0;
    }
    

    问题注意

    e[++cnt].next = head[u];
    e[cnt].to = v;
    head[u] = cnt;
    

    打成

    e[cnt++].next = head[u];
    e[cnt].to = v;
    head[u] = cnt;
    
  • 相关阅读:
    复利计算--结对1.0,做汉堡,结对2.0
    复利计算1.0,2.0,3.0,4.0,5.0
    2020助教总结
    作业2
    作业一
    linux设置opengl版本
    第一次个人作业
    寒假助教总结
    直播
    2020面向对象程序设计寒假作业3
  • 原文地址:https://www.cnblogs.com/xuanfly/p/11823509.html
Copyright © 2011-2022 走看看