代码随想录第58天

卡码网:117. 软件构建

n,m = map(int,input().split())
st = [[] for _ in range(n)]
dp = [0]*n
stack = []
for i in range(m):
    indegree,outdegree = map(int,input().split())
    dp[outdegree]+=1
    st[indegree].append(outdegree)
ans = []
for i in range(n):
    if dp[i]==0:
        stack.append(i)
while stack:
    d = stack.pop(0)
    ans.append(str(d))
    for i in st[d]:
        dp[i]-=1
        if dp[i]==0:
            stack.append(i)
if sum(dp)==0:
    print(' '.join(ans))
else:print('-1')

卡码网:47. 参加科学大会

#include <iostream>
#include <vector>
#include <queue>
#include <set>
#include <climits>

using namespace std;

struct Node {
    int id;
    int price;
};



int main() 
{
    int n, m;
    cin >> n >> m;
    // 先用邻接表表示图
    vector<vector<Node>> grap(n +1); // 0号车站不存在 从1号车站开始
    int tmpM = m;
    while(tmpM--) {
        int s, e, v;
        cin >> s >> e >> v;
        Node node;
        node.id = e;
        node.price = v;
        grap[s].push_back(node);
    }
    
    queue<Node> que;
    int end = n;
    Node start;
    start.id = 1;
    start.price = 0; //11 不需要任何花费
    que.push(start);
    vector<int> mincost(n+1, INT_MAX); //1到其他节点的最小距离
    int ans = INT_MAX;
    while(!que.empty()) {
        auto cur = que.front(); que.pop();
        int curId = cur.id;
        int curPrice = cur.price;
        for(int i = 0; i < grap[curId].size(); i++) {
            int nxtId = grap[curId][i].id;
            int nxtPrice = grap[curId][i].price;
            if(curPrice + nxtPrice < mincost[nxtId]) {
                // 加入队列
                Node node;
                node.id = nxtId;
                node.price = curPrice + nxtPrice;
                
                que.push(node);
                mincost[nxtId] = curPrice + nxtPrice;
                if(nxtId == end){
                    ans = min(ans, mincost[nxtId]);
                }
            }
        }
        
    }
    cout << (ans ==INT_MAX ? -1 : ans) << endl; // 如果没有在把队列遍历完还没找到 那么就不可达
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值