HDU - 3666 差分约束 + 对数

来源:互联网 发布:外国人交友的软件 编辑:程序博客网 时间:2024/05/01 08:01

题意:

给出一个矩阵c以及L和U,判断出是否存在两个序列a1,a2...an和b1,b2,..bm,使得满足: a[i] / b[j] * c[i][j] <= U && a[i] / b[j] * c[i][j] >= L

思路:

查分约束。
根据题意可以列出如下的关系式:
a[i] / b[j] <= U / c[i][j] 
b[j] / a[i] <= c[i][j] / L
这时候利用对数,将除法转化成减法,得到:
log(a[i]) - log(b[j]) <= log(U / c[i][j])
log(b[j]) - log(a[i]) <= log(c[i][j] / L)
这样就是典型的差分约束的形式了,因为这道题,很显然是个连通图,所以直接任意选择一个节点来进行spfa寻找负圈即可。
但是判断条件是入队大于n会超时,网上有人写的是判断是否大于sqrt(n)就能过,也不会证明,还有一种方法是手动模拟栈或队列也能水过。

代码:

#include <cstdio>#include <cstring>#include <vector>#include <algorithm>#include <cmath>#include <iostream>#include <queue>using namespace std;const int MAXN = 444 * 2;const int INF = 0x3f3f3f3f;const double eps = 1e-6;struct Edge {int from, to;double dist;};struct SPFA {int n, m;vector <Edge> edges;vector <int> G[MAXN];bool vis[MAXN];double d[MAXN];int cnt[MAXN];void init(int n) {this -> n = n;for (int i = 0; i < n; i++) G[i].clear();edges.clear();}void AddEdge(int from, int to, double dist) {edges.push_back((Edge) {from, to, dist});m = edges.size();G[from].push_back(m - 1);}bool solve(int s) {queue <int> q;    memset (vis, false, sizeof vis);    memset (cnt, 0, sizeof(cnt));    for (int i = 0; i < n; i++) d[i] = INF;    vis[s] = true; d[s] = 0; cnt[s] = 1; q.push (s);    while (!q.empty ()) {        int u = q.front (); q.pop ();        vis[u] = false;        for (int i = 0; i < (int)G[u].size(); i++) {            Edge& e = edges[G[u][i]];            if (d[e.to] > d[u] + e.dist) {                d[e.to] = d[u] + e.dist;                if (!vis[e.to]) {                    vis[e.to] = true; q.push (e.to);                    if (++cnt[e.to] > (int) sqrt(n))                        return false;                }            }        }    }    return true;}} spfa;int c[MAXN][MAXN];int main() {int n, m, L, U;while (scanf("%d%d%d%d", &n, &m, &L, &U) == 4) {spfa.init(n + m);for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {scanf("%d", &c[i][j]);spfa.AddEdge(j + n, i, log10(1.0 * U / c[i][j]));spfa.AddEdge(i, j + n, log10(1.0 * c[i][j] / L));}}if (spfa.solve(0)) puts("YES");else puts("NO");}return 0;}


0 0
原创粉丝点击