CSU1978: LXX的图论题

CSU1978: LXX的图论题

Description

由于lxx的图论和数据结构太弱了,大佬Z决定为lxx补一补。于是大佬Z为lxx出了一道题目,题目如下:给出一张有向图,图中有n个点,m条边,每条边上都有一个权值w,问图中是否存在满足以下条件的点i,j,...p使得不等式w[i][j] * w[j][k] * .... * w[p][i]<1成立。奈何lxx太弱了,他决定寻求你的帮助。

Input

多组输入,以文件结尾。第一行两个整数n( 1<=n<=500 ),m( 1<=m<=n*(n-1)/2 ),接下来m行,每行3个数x,y,z,(x≠y):表示x到y有一条边,权值为z(0<z<20,且保证z小数点后面最多只有一位)。

Output

如果存在满足题目所描述的式子,输出“YES”,否则输出“NO”。

Sample Input

2 2
1 2 0.9
2 1 1.2
6 4
1 2 0.1
2 4 0.8
4 1 12
4 1 15

Sample Output

NO
YES 

Hint

点的编号为1~n

Source

2017年8月月赛

Author

廖璇璇

题目就叫图论题,加上题中给出了“w[i][j] * w[j][k] * …. * w[p][i]<1”的约束条件,容易想到最短路算法,并且这个最短路是带有负环的,加上顶点数量不多,所以可以循环地调用递归的SPFA来检查每一个顶点。若存在从某个顶点出发又回到出发点的负环,并且路径权值之积小于1,就可以中断并输出结果了。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 504, INF = 0x7fffffff;

int n, m, cnt, start;
bool flag;
int u[maxn*maxn], v[maxn*maxn], first[maxn*maxn], Next[maxn*maxn]; // 注意预留足够的空间存储边。
double w[maxn*maxn], d[maxn]; // 注意权值为浮点型。
bool vis[maxn];

void init(){
    memset(first, -1, sizeof(first));
    memset(Next, -1, sizeof(Next));
    for(int i = 0; i < maxn; i++)
        d[i] = INF;
    cnt = 0;
    flag = false;
}

void makeEdge(int a, int b, double x){
    u[cnt] = a;
    v[cnt] = b;
    w[cnt] = x;
    Next[cnt] = first[a];
    first[a] = cnt++;
}

void spfa(int now){
    if(flag) return;
    vis[now] = true;
    for(int i = first[now]; i != -1; i = Next[i]){
        if(flag) return;
        int to = v[i];
        if(d[to] > d[now]*w[i]){
            d[to] = d[now]*w[i];
            if(to == start && d[to]<1){ // 存在符合条件的负环即中断。
                flag = true;
                return;
            }
            else
                spfa(to);
        }
    }
    vis[now] = false;
}

int main(){
#ifdef TEST
freopen("test.txt", "r", stdin);
#endif // TEST

    while(cin >> n >> m){
        init();
        int a, b; double c;
        for(int i = 0; i < m; i++){
            scanf("%d%d%lf", &a, &b, &c);
            makeEdge(a, b, c);
        }
        for(int i = 1; i <= n; i++){
            start = i;
            memset(vis, false, sizeof(vis));
            for(int j = 0; j <= n; j++)
                d[j] = INF;
            d[i] = 1; // 到自己的权值赋1,准备与其他权值相乘。
            spfa(i);
            if(flag) break;
        }
        if(flag)
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}

/**********************************************************************
    Problem: 1978
    User: xyJiang
    Language: C++
    Result: AC
    Time:120 ms
    Memory:25168 kb
**********************************************************************/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值