【poj2983】 Is the Information Reliable?
生活随笔
收集整理的這篇文章主要介紹了
【poj2983】 Is the Information Reliable?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http://poj.org/problem?id=2983?(題目鏈接)
一個SB錯誤TLE了半個小時。。。
題意
一條直線上有n個點,給出m條信息,若為P則表示點A在點B的北方X米,若為V則表示A在B的北方。判斷給出的信息是否合法。
Solution
對于P,A-B=X等價于是A-B>=X && A-B<=X(B-A>=-X)。
對于V,A-B>=1。
所以我們就可以利用差分約束去求解這個問題,在圖上跑SPFA最長路判斷是否存在正環。
注意設置一個超級源點使得圖聯通。
代碼
// poj2983 #include<algorithm> #include<iostream> #include<cstdlib> #include<cstring> #include<cstdio> #include<cmath> #include<queue> #define LL long long #define inf 2147483640 #define Pi acos(-1.0) #define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout); using namespace std; inline LL getint() {int f,x=0;char ch=getchar();while (ch<='0' || ch>'9') {if (ch=='-') f=-1;else f=1;ch=getchar();}while (ch>='0' && ch<='9') {x=x*10+ch-'0';ch=getchar();}return x*f; }const int maxn=1010,maxm=100010; struct edge {int to,next,w;}e[maxm<<2]; int head[maxn],dis[maxn],vis[maxn],cnts[maxn],n,cnt,m;void link(int u,int v,int w) {e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;e[cnt].w=w; } bool SPFA() {deque<int> q;for (int i=1;i<=n;i++) dis[i]=-inf,cnts[i]=0,vis[i]=0;q.push_back(n+1);dis[n+1]=0;vis[n+1]=1;cnts[n+1]=1;while (!q.empty()) {int x=q.front();q.pop_front();vis[x]=0;for (int i=head[x];i;i=e[i].next)if (dis[e[i].to]<dis[x]+e[i].w) {dis[e[i].to]=dis[x]+e[i].w;if (!vis[e[i].to]) {if (++cnts[e[i].to]>n) return 1;vis[e[i].to]=1;if (!q.empty() && dis[e[i].to]<dis[q.front()]) q.push_back(e[i].to);else q.push_front(e[i].to);}}}return 0; } int main() {while (scanf("%d%d",&n,&m)!=EOF) {for (int i=1;i<=n+1;i++) head[i]=0;cnt=0;while (m--) {int u,v,w;char ch[5];scanf("%s ",ch);if (ch[0]=='P') {scanf("%d%d%d",&u,&v,&w);link(v,u,w);link(u,v,-w);}else {scanf("%d%d",&u,&v);link(v,u,1);}}for (int i=1;i<=n;i++) link(n+1,i,0);if (SPFA()) puts("Unreliable");else puts("Reliable");}return 0; }
轉載于:https://www.cnblogs.com/MashiroSky/p/5914106.html
總結
以上是生活随笔為你收集整理的【poj2983】 Is the Information Reliable?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html中盒子模型立体结构图
- 下一篇: 在线小词典(mysql扩展库操作)