sgu 213 分类: sgu 2015-06...


SPFA最短路,dist(st)即为最少颜色数,
答案可以这样构造:对于一条边(u,v),染色为min(max(dist(u),dist(v)),dist(t))


为什么可以这么构造?

我们可以发现,所有边都为1的情况下, 对于一条边(u,v), dist(v)<=dist(u)+1

dist 的取值,可以把原图划分成一个层次图,
这样就可以保证起点到终点最少跨过dist(t)层,

那么只要把连接两个不在同一层的结点的边染色,
这样就可以保证起点到终点最少经过了dist(t)种不同颜色。



#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>

#include<ctime>
#include<cmath>

const int maxn = 405, INF = 0x3f3f3f3f;
#define fr first
#define to second
#define mp(x,y) std::make_pair(x,y)
#define pb(x) push_back(x)

int n, m, s, t;
bool w[maxn][maxn];
int dist[maxn];
bool hash[maxn];
std::queue<int> line;
std::pair<int,int> edge[maxn*maxn];
std::vector<int> color[maxn*maxn];

int SPFA()
{
    memset(dist,INF,sizeof(dist));

    dist[s] = 0, line.push(s), hash[s] = true;

    while(true)
    {
        if(line.empty()) break;

        int u = line.front(); 
        hash[u] = false, line.pop();

        for(int i = 1; i <= n; i++)
            if(w[u][i] && dist[u]+1 < dist[i])
            {
                dist[i] = dist[u]+1;
                if(!hash[i]) 
                    line.push(i), hash[i] = true;
            }   
    }

    return dist[t];
}

void prtcolor()
{
    for(int i = 1; i <= m; i++)
    {
        int opt = std::max(dist[edge[i].fr], dist[edge[i].to]);
        color[std::min(opt, dist[t])].pb(i);
    }

    for(int i = 1; i <= dist[t]; i++)
    {
        std::cout << color[i].size();
        for(int j = 0; j < color[i].size(); j++)
            std::cout << ' ' << color[i][j];
        std::cout << std::endl; 
    }
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("sgu213.in","r",stdin);
    freopen("sgu213.out","w",stdout);
#endif

    std::cin >> n >> m >> s >> t;

    for(int i = 1, u, v; i <= m; i++)
    {
        std::cin >> u >> v, edge[i] = mp(u,v);
        w[u][v] = w[v][u] = true;
    }

    std::cout << SPFA() << std::endl, prtcolor();

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;       
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/dashgua/p/4722998.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值