Minimum Or Spanning Tree(代码源每日一题)
Minimum Or Spanning Tree(代码源每日一题)
Minimum Or Spanning Tree - 题目 - Daimayuan Online Judge
贪心,最小生成树
- 由于生成树的代价是各边权值的按位或,因此按位数从大到小贪心
- 若当前位能全用 0 边构成生成树就全用 0 边,答案的这一位就是 0,并把 1 边全部删掉
- 若当前位不能全用 0 边构成生成树,答案的这一位就是 1,并保留所有边,这样对更低的位选边而言是更优的
- 注意应先把 1 边全部记录下来,等确定不能用 0 边构成再删掉,不能找到 1 边就删
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
#define endl "\n"
typedef long long ll;
typedef pair<int, int> PII;
const int N = 1e5 + 10;
int a[N], s[N];
int n;
int mp[N];
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
s[i] = (s[i-1] + a[i]) % n;
}
for (int i = 1; i <= n; i++)
{
if (s[i] == 0)
{
cout << i << endl;
for (int j = 1; j <= i; j++)
cout << j << " ";
cout << endl;
return 0;
}
}
for (int i = 1; i <= n; i++)
{
if (mp[s[i]] == 0)
mp[s[i]] = i;
else
{
cout << i - mp[s[i]] << endl;
for (int j = mp[s[i]] + 1; j <= i; j++)
cout << j << " ";
cout << endl;
return 0;
}
}
return 0;
}