您的位置:首页 > 其它

POJ 1364 King (差分约束)

2017-09-20 18:44 309 查看
解题思路:

如果不能构造出这个数列,那么一定存在两个表达式互相矛盾,例如: s[3] - s[1] >= 3  && s[3]-s[1]<=2 

在图内表现的效果就是存在环,最长路则存在正环,最短路则存在负环。

SPFA求最长路判环即可,注意添加超级源点,把图变成连通图。

AC代码:

/*
* @Author: wchhlbt
* @Last Modified time: 2017-09-20
*/

#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <limits>
#include <climits>
#include <cstdio>

#define Fori(x) for(int i=0;i<x;i++)
#define Forj(x) for(int j=0;j<x;j++)
#define maxn 1007
#define inf 0x3f3f3f3f
#define ONES(x) __builtin_popcount(x)
#define pb push_back
#define AA first
#define BB second
#define _ << " " <<
using namespace std;

typedef long long ll ;
const double eps =1e-8;
const int mod = 998244353;
const double PI = acos(-1.0);
int dx[5] = {0,0,1,-1,0};
int dy[5] = {1,-1,0,0,0};
inline int read(){ int cnt; scanf("%d",&cnt); return cnt;}

//每次使用前需要调用init函数初始化 可以处理负权边
//最坏复杂度O(V*E)
int d[maxn],inq[maxn];//inq数组储存当前点是否在队列中
int deg[maxn];//记录每个节点入队次数
vector<pair<int,int> > e[maxn]; //pair<节点, 边权>

int n,m;

void init()
{
for(int i = 0; i<maxn; i++){
e[i].clear();
d[i] = -inf;
inq[i] = 0;
deg[i] = 0;
}
}
int SPFA(int s)//s为起点
{
queue<int> Q;
Q.push(s); d[s] = 0; inq[s] = 1; deg[s] = 1;
while(!Q.empty()){
int hd = Q.front();
Q.pop(); inq[hd] = 0;
for(int i = 0; i<e[hd].size(); i++){
int u = e[hd][i].first;
int v = e[hd][i].second;
if(d[u]<d[hd]+v){
d[u] = d[hd] + v;
if(inq[u]==1) continue;
inq[u] = 1;
deg[u]++;
if(deg[u]>n+1) return -1;
Q.push(u);
}
}
}
return 1;
}

char str[20];
int main()
{
while(~scanf("%d",&n) && n)
{
int m = read();
init();
for(int i = 1; i<=m; i++){
int a,b,c;
scanf("%d %d %s %d",&a,&b,str,&c);
if(str[0]=='l')
e[a+b].pb(make_pair(a-1,1-c));
else
e[a-1].pb(make_pair(a+b,c+1));
}
for(int i = 0; i<=n; i++){
e[n+2].pb(make_pair(i,0));
}
int res = SPFA(n+2);
if(res==1) puts("lamentable kingdom");
else puts("successful conspiracy");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: