POJ 1364 King (差分約束系統)

題意大致是:給你一些關於一個數列的條件,問你這樣的數列是否存在。比如a[k]+...a[k+ni-1]>x 或者 a[k]+...a[k+ni-1]<x

思路:直接表達成前綴和,這樣就會出現形如 d(v)<=d(u)+w(u,v)的形式,然後去跑BellmanFord。(因爲只要判斷有沒有負圈,所以不用超級源點)


#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
#include<stdio.h>
#include<vector>
using namespace std;



int n,m;

struct Edge
{
    int from;
    int to;
    int w;
};
vector<Edge> E;
char ope[120];
int dis[120];

void init()
{
    E.clear();
}

bool Bellman_ford()
{
    memset(dis,0,sizeof(dis));
    int size=E.size();
    for(int i=0;i<=n;i++)
    {
        for(int j=0;j<size;j++)
        {
            int from=E[j].from;
            int to=E[j].to;
            int w=E[j].w;
            if(dis[to]>dis[from]+w)
            {
                dis[to]=dis[from]+w;
            }
        }
    }

    for(int j=0;j<size;j++)
    {
       int from=E[j].from;
        int to=E[j].to;
        int w=E[j].w;
        if(dis[to]>dis[from]+w)
        {
            return false;
        }
    }

    return true;
}

int main()
{
    while(cin>>n)
    {
        if(n==0) break;
        cin>>m;
        init();
        for(int i=0;i<m;i++)
        {
            int a,b,x;
            scanf("%d %d",&a,&b);
            scanf("%s",ope);
            scanf("%d",&x);
            if(strcmp(ope,"lt")==0)
            {
                Edge temp;
                temp.from=a-1;
                temp.to=a+b;
                temp.w=x-1;

                E.push_back(temp);
            }
            else
            {
                Edge temp;
                temp.from=a+b;
                temp.to=a-1;
                temp.w=-(1+x);
                E.push_back(temp);
            }
        }

        bool has=Bellman_ford();
        if(has==false)
        {
            printf("successful conspiracy\n");
        }
        else printf("lamentable kingdom\n");
    }


    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章