您的位置:首页 > 其它

hdu 5385 The path 2015多校联合训练赛#8 bfs

2015-08-14 10:40 323 查看


The path

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 282 Accepted Submission(s): 76

Special Judge


Problem Description

You have a connected directed graph.Let d(x) be
the length of the shortest path from 1 to x.Specially d(1)=0.A
graph is good if there exist x satisfy d(1)<d(2)<....d(x)>d(x+1)>...d(n).Now
you need to set the length of every edge satisfy that the graph is good.Specially,if d(1)<d(2)<..d(n),the
graph is good too.

The length of one edge must ∈ [1,n]

It's guaranteed that there exists solution.



Input

There are multiple test cases. The first line of input contains an integer T,
indicating the number of test cases. For each test case:

The first line contains two integers n and m,the number of vertexs and the number of edges.Next m lines contain two integers each, ui and vi (1≤ui,vi≤n),
indicating there is a link between nodes ui and vi and
the direction is from ui to vi.

∑n≤3∗105,∑m≤6∗105

1≤n,m≤105



Output

For each test case,print m lines.The
i-th line includes one integer:the length of edge from ui to vi



Sample Input

2
4 6
1 2
2 4
1 3
1 2
2 2
2 3
4 6
1 2
2 3
1 4
2 1
2 1
2 1




Sample Output

1
2
2
1
4
4
1
1
3
4
4
4




Source

2015 Multi-University Training Contest 8

每个点距离1-n,知道距离后,U-v的边就是abs(dist[u]-dist[v])

所以从1,n两个方向开始bfs

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<set>
using namespace std;
#define maxn 100007

int head[maxn];
int cnt;
struct Edge{
    int v,u,next;
};
int dist[maxn];
Edge edge[maxn];
void addedge(int u,int v){
    edge[cnt].v = v;
    edge[cnt].u = u;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}
int check[maxn];
int main(){
    int t,n,m;
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&m);
        cnt = 0;
        for(int i = 0;i <= n; i++){
            check[i] = 0;
            head[i] = -1;
        }
        int u,v;
        for(int i = 0;i < m; i++){
            scanf("%d%d",&u,&v);
            addedge(u,v);
        }
        check[1] = 1;
        check
 = 1;
        int l = 1, r = n;
        for(int i = 1;i <= n; i++){
            if(check[l] == 0)
                u = r--;
            else u = l++;
            dist[u] = i;
            for(int j = head[u]; j != -1; j=edge[j].next){
                v = edge[j].v;
                check[v] = 1;
            }
        }
        for(int i = 0;i < m; i++){
            u = edge[i].u;
            v = edge[i].v;
            if(dist[u] < dist[v])
                printf("%d\n",dist[v]-dist[u]);
            else printf("%d\n",n);
        }

    }
    return 0;
}

/*
22
4 3
1 2
1 4
4 3
4 6
1 2
2 4
1 3
1 2
2 2
2 3
4 6
1 2
2 3
1 4
2 1
2 1
2 1
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: