图论相关问题

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;
}
相关推荐
秋夫人26 分钟前
B+树(B+TREE)索引
数据结构·算法
梦想科研社1 小时前
【无人机设计与控制】四旋翼无人机俯仰姿态保持模糊PID控制(带说明报告)
开发语言·算法·数学建模·matlab·无人机
Milo_K1 小时前
今日 leetCode 15.三数之和
算法·leetcode
Darling_001 小时前
LeetCode_sql_day28(1767.寻找没有被执行的任务对)
sql·算法·leetcode
AlexMercer10121 小时前
【C++】二、数据类型 (同C)
c语言·开发语言·数据结构·c++·笔记·算法
Greyplayground1 小时前
【算法基础实验】图论-BellmanFord最短路径
算法·图论·最短路径
蓑 羽1 小时前
力扣438 找到字符串中所有字母异位词 Java版本
java·算法·leetcode
源代码:趴菜1 小时前
LeetCode63:不同路径II
算法·leetcode·职场和发展
儿创社ErChaungClub2 小时前
解锁编程新境界:GitHub Copilot 让效率翻倍
人工智能·算法
前端西瓜哥2 小时前
贝塞尔曲线算法:求贝塞尔曲线和直线的交点
前端·算法