JZOJ 3786. 【NOI2015模拟8.19】图
生活随笔
收集整理的這篇文章主要介紹了
JZOJ 3786. 【NOI2015模拟8.19】图
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Description
給定一個 n 個點 m 條邊的無向圖,進行多次詢問,每次詢問點 a 是否能經過恰好 c 條邊到達點 b(當然,可以對于一條邊可以來回經過多次) 。
Input
第一行三個數 n,m,q,其中 q 表示詢問數。
接下來 q 行,每行三個數 a,b,c。
Output
對于每次詢問,如果存在一種走法,輸出 TAK,否則輸出 NIE
Sample Input
8 7 4
1 2
2 3
3 4
5 6
6 7
7 8
8 5
2 3 1
1 4 1
5 5 8
1 8 10
Sample Output
TAK
NIE
TAK
NIE
Data Constraint
對于 50%的數據,n<=800。
對于 100%的數據,2<=n<=5000,1<=m<=5000,1<=q<=1000000,1<=a,
b<=n,1<=c<=10^9。
Solution
分走的步長的奇偶性以每個點為源點各做一遍SPFA(無松弛操作),只需多開一維0/1即可。
直接判斷 c 是否大于等于 a 到 b 的最短路并判斷奇偶性。
因為可以在一條邊上不斷重復走(兩步兩步地走,奇偶性不變)。
注意特判自環且沒出邊的情況。
時間復雜度 O(N2+Q) 。
Code
#include<cstdio> #include<cstring> #include<cctype> using namespace std; const int N=5005; int tot; int first[N],next[N<<1],en[N<<1]; int q[N*N/3][2],dis[N][N][2],d[N]; inline int read() {int X=0,w=0; char ch=0;while(!isdigit(ch)) w|=ch=='-',ch=getchar();while(isdigit(ch)) X=(X<<3)+(X<<1)+(ch^48),ch=getchar();return w?-X:X; } inline void insert(int x,int y) {next[++tot]=first[x];first[x]=tot;en[tot]=y;d[x]++; } inline void spfa(int s) {memset(dis[s],60,sizeof(dis[s]));int l=dis[s][q[1][0]=s][0]=0,r=1;while(l<r){int x=q[++l][0],y=q[l][1];for(int i=first[x];i;i=next[i])if(dis[s][x][y]+1<dis[s][en[i]][y^1]){dis[s][en[i]][y^1]=dis[s][x][y]+1;q[++r][0]=en[i];q[r][1]=y^1;}} } int main() {int n=read(),m=read(),q=read();for(int i=1;i<=m;i++){int x=read(),y=read();insert(x,y);insert(y,x);}for(int i=1;i<=n;i++) spfa(i);while(q--){int x=read(),y=read(),z=read();if(x==y && !d[x]) puts("NIE"); elseputs(z>=dis[x][y][z&1]?"TAK":"NIE");}return 0; }總結
以上是生活随笔為你收集整理的JZOJ 3786. 【NOI2015模拟8.19】图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JZOJ 3660. 【SHTSC201
- 下一篇: JZOJ 3775. 【NOIP2014