Блог пользователя harvey_wzy

Автор harvey_wzy, история, 5 часов назад, По-английски

1017D - The Wu

I write a solution of O(4^n), and it gets TLE on test 4. I found a code which is also O(4^n) and passed in 300ms, deleted three blocks of my code, and insert 3 blocks from another code and then, a miracle happened — it gets TLE.

My code is here:

// Problem: D. The Wu
// Contest: Codeforces - Codeforces Round 502 (in memory of Leopoldo Taravilse, Div. 1 + Div. 2)
// URL: https://codeforces.net/problemset/problem/1017/D
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
using namespace std;

int w[15], cnt[4100];
int ans[4100][105];

void dfs(int u, int v, int n, int pos, int sum) {
	if (pos == n) {
		ans[u][min(sum, 101)] += cnt[v];
		return;
	}
	int x = (u >> pos) & 1;
	dfs(u, v | (x << pos), n, pos + 1, sum + w[pos]);
	dfs(u, v | ((x ^ 1) << pos), n, pos + 1, sum);
}

int main() {
	int n, m, q;
	scanf("%d %d %d", &n, &m, &q);
	for (int i = 0; i < n; i++) {
		scanf("%d", &w[n - i - 1]);
	}
	for (int i = 0; i < m; i++) {
		string s;
		cin >> s;
		int x = 0;
		for (char ch : s) {
			x = (x << 1) + (ch == '1');
		}
		cnt[x]++;
	}
	for (int i = 0; i < (1 << n); i++) {
		dfs(i, 0, n, 0, 0);
		for (int j = 1; j <= 100; j++) {
			ans[i][j] += ans[i][j - 1];
		}
	}
	while (q--) {
		string s;
		int lim;
		cin >> s >> lim;
		int x = 0;
		for (char ch : s) {
			x = (x << 1) + (ch == '1');
		}
		printf("%d\n", ans[x][lim]);
	}
}
  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
4 часа назад, # |
  Проголосовать: нравится +10 Проголосовать: не нравится

scanf and printf are garbage, use cin and cout instead: 286224806

  • »
    »
    3 часа назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    wait..I think scanf and printf is faster than cin ,why not use read(),IO

  • »
    »
    64 минуты назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    All of C/C++ default IO are garbage 286250631.

»
8 минут назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится
#define fast_io         ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

use this.