图论相关问题

1. 拓扑排序+bitset

第一次使用bitset,复杂度:N/32,比N小

所以总的时间复杂度为O(N*(N+M)/32)

cpp 复制代码
#include <iostream>
#include <bitset>
#include <queue>
using namespace std;
const int N = 3e4+20;
bitset<N> f[N];
struct NODE{
    int to, next;
}edge[N];
int head[N], cnt, inv[N], n, m;
void add(int u, int v) {
    ++cnt;
    edge[cnt].to = v, edge[cnt].next = head[u], head[u] = cnt;
}

void topo() {
    queue<int> q;
    for(int i=1; i<=n; i++) {
        if(!inv[i]) q.push(i);
    }
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        f[x][x] = 1; //自己可到达
        for(int i = head[x]; i; i = edge[i].next) {
            int v = edge[i].to;
            f[v] |= f[x];
            inv[v]--;
            if(!inv[v]) q.push(v);
        }
    }
    
    for(int i=1; i<=n; i++) printf("%d\n", f[i].count()); //二进制中1的个数
}

int main() {
    int u, v; scanf("%d%d", &n, &m);
    while(m--){
        scanf("%d%d", &u, &v);
        add(v, u); //反向建图
        inv[u]++;
    }
    topo();
    return 0;
}
2. 01分数规划, spfa判断正环

题目链接:Acwing 观光奶牛

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1050, M = 5005;
int head[N], cnt, n, ct[N], st[N];
double dis[N], f[N];
struct NODE{
    int to, next, w;
}edge[M];

void add(int u, int v, int w){
    ++cnt;
    edge[cnt].to = v, edge[cnt].next = head[u], head[u] = cnt;
    edge[cnt].w = w;
}

bool spfa(double mid) {
    queue<int> q;
    for(int i=1; i<=n; i++) q.push(i), st[i] = true, dis[i] = ct[i] = 0;
    
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        st[x] = false;
        for(int i = head[x]; i; i = edge[i].next) {
            int v = edge[i].to;
            if( dis[v] < dis[x] + f[x] - mid * edge[i].w) { //判断正环
                dis[v] = dis[x] + f[x] - mid * edge[i].w;
                ct[v] = ct[x]+1;
                if(ct[v] >= n) return true;
                if(!st[v]) {
                    q.push(v), st[v] = true;
                }
            }
        }
    }
    
    return false;
}
int main() {
    int p; scanf("%d%d", &n, &p);
    for(int i=1; i<=n; i++) cin >> f[i];
    int a, b, w;
    while(p--) {
        scanf("%d%d%d", &a, &b, &w);
        add(a, b, w);
    }
    double l = 0, r = 1010, eps = 1e-4;
    while(r-l > eps) {
        double mid = (l+r)/2;
        if(spfa(mid)) l = mid;
        else r =mid;
    }
    printf("%.2lf", l);
    return 0;
}
相关推荐
Fanxt_Ja3 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下3 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶3 小时前
算法 --- 字符串
算法
博笙困了4 小时前
AcWing学习——差分
c++·算法
NAGNIP4 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP4 小时前
大模型微调框架之LLaMA Factory
算法
echoarts4 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客4 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法
徐小夕4 小时前
花了一天时间,开源了一套精美且支持复杂操作的表格编辑器tablejs
前端·算法·github
小刘鸭地下城4 小时前
深入浅出链表:从基础概念到核心操作全面解析
算法