二分图最大匹配,建图
本题要点:
1、左部节点:学生, 学生的范围 m <= 60
右部节点:排名, 名次的范围 n <= 100000
每个学生与之对应的可能的排名,都连线。
2、题目要求输出最大的匹配数,然后输出学生的序号,按字典序最大的输出。
套用 增广路模板,扫描m个学生时候,从 m 到 1 扫描,这样优先给
序号大的学生安排排名。最后的结果就是 最大的字典序。
3、 增加一个数组,res, res[i] == 1 表示学生i有匹配的排名
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MaxN = 100010, MaxStu = 70;
int match[MaxN], res[MaxStu], cnt;
bool vis[MaxN];
int T, n, m;
struct node
{
int a, b;
}stu[MaxStu];
bool dfs(int x)
{
for(int y = stu[x].a; y <= stu[x].b; ++y)
{
if(vis[y])
continue;
vis[y] = true;
if(!match[y] || dfs(match[y]))
{
match[y] = x;
res[x] = 1; //这名学生有匹配
return true;
}
}
return false;
}
int main()
{
scanf("%d", &T);
while(T--)
{
memset(res, 0, sizeof res);
memset(match, 0, sizeof match);
scanf("%d", &m); //学生人数
for(int i = 1; i <= m; ++i)
{
scanf("%d%d", &stu[i].a, &stu[i].b);
}
int ans = 0;
for(int i = m; i >= 1; --i)
{
memset(vis, false, sizeof vis);
if(dfs(i))
++ans;
}
printf("%d\n", ans);
cnt = 0;
for(int i = 1; i <= m; ++i)
{
if(1 == res[i])
{
++cnt;
if(cnt == ans) printf("%d\n", i);
else printf("%d ", i);
}
}
}
return 0;
}
/*
2
4
5004 5005
5005 5006
5004 5006
5004 5006
7
4 5
2 3
1 2
2 2
4 4
2 3
3 4
*/
/*
3
2 3 4
5
1 3 5 6 7
*/