POJ 3613 Cow Relays
[Problem]
给定m(<=100)条边的无向图,询问从s点到t点经过k条边的最短路径。 k (1e6)
[Solution]
我们定义一种操作(类似于矩阵乘)
c[i][j] = min(a[i][k] + b[k][j]) (1 <=k<=n )
容易证明此操作满足结合律
令该图的矩阵为a,则答案为a^k
[Code]
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
#include<map>
#include<cstring>
using namespace std;
typedef long long ll;
#define maxn 200
#define inf 0x3f3f3f3f3f3f3f3f
int n, m, cnt, s, t, tim;
map<int , int > conn;
int id(int x)
{
if (!conn.count(x)) conn[x] = ++cnt;
return conn[x];
}
struct matrix {
ll m[maxn][maxn];
matrix(){
memset(m, inf, sizeof(m));
}
};
matrix mul(matrix a, matrix b)
{
matrix c;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
c.m[i][j] = inf;
for(int k = 1; k <= n; k++)
c.m[i][j] = min(c.m[i][j], a.m[i][k] + b.m[k][j]);
}
}
return c;
}
matrix quickpow(matrix a, int b)
{
matrix tot = a;
b--;
while(b > 0){
if (b % 2 == 1) tot = mul(tot, a);
a = mul(a, a);
b /= 2;
}
return tot;
}
int main()
{
// freopen("b.in", "r", stdin);
scanf("%d%d%d%d", &tim, &m, &s, &t);
cnt = 0;
matrix base;
for(int i = 1; i <= m; i++){
int x, y, z;
scanf("%d%d%d", &z, &x, &y);
x = id(x); y = id(y);
base.m[x][y] = z;
base.m[y][x] = z;
}
n = cnt;
s = id(s); t = id(t);
ll ans = quickpow(base, tim).m[s][t];
cout << ans;
return 0;
}
POJ 3190 Stall Reservations
[Solution]
首先把每头牛的区间排序,按照升序依次为每头牛分配stall
把每个stall的结束时间放到一个优先队列,每次取出结束时间最靠前的机器,判断这个stall是否可以为这头牛服务,否的话加入一个新的stall
[Code]
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
#define N 220000
int n, m;
struct node{
int pos, l, r;
bool operator <(const node &a) const {
if (r == a.r) return l > a.l;
return r > a.r;
}
} a[N];
int ans[N];
priority_queue<node> q;
bool cmp(node a, node b)
{
if (a.l == b.l) return a.r < b.r;
return a.l < b.l;
}
int main()
{
//freopen("b.in", "r", stdin);
while(~scanf("%d", &n)){
int cnt = 0;
while(!q.empty()) q.pop();
for(int i = 1; i <= n; i++) scanf("%d%d", &a[i].l, &a[i].r);
for(int i = 1; i <= n; i++) a[i].pos = i;
sort(a + 1, a + n + 1, cmp);
for(int i = 1; i <= n; i++) {
int l = a[i].l, r = a[i].r, pos = a[i].pos;
if (q.empty() || q.top().r >= l){
node res;
res.pos = ++cnt;
res.l = l;
res.r = r;
ans[pos] = cnt;
q.push(res);
}
else {
node res = q.top();
q.pop();
res.l = l;
res.r = r;
ans[pos] = res.pos;
q.push(res);
}
}
printf("%d\n", cnt);
for(int i = 1; i <= n; i++) printf("%d\n", ans[i]);
}
return 0;
}