暑期集训补题系列Day2--模拟/暴力求解进阶

Day 2–模拟/暴力求解进阶

E - String Typing Codeforces 954B
substr用法: s.substr(i,j)表示从下标为i的位置开始截取j位

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,len=1;
    string s;
    cin>>n>>s;
    for(int i=1; i<=n; i++)
        if(s.substr(0,i)==s.substr(i,i))///s.substr(i,j)表示从下标为i的位置截取j位字符,判断最长循环节
            len=i;
    cout<<n-len+1<<endl;
    return 0;
}

I - Game of Robots Codeforces 670B
题意:

n 个机器(标号唯一)人站一列按照一定的规则进行报号游戏,问报出的第 k 个编号是什么

#include<stdio.h>
const int MYDD=1e5+1103;
 
int robot[MYDD];
 
int main() {
	int n,k;
	while(scanf("%d%d",&n,&k)!=EOF) {
		for(int j=1; j<=n; j++)
			scanf("%d",&robot[j]);
		for(int i=1; i<=n; i++) {
			if(k-i>0)	k=k-i;
			else		break;
		}\
		printf("%d\n",robot[k]);
	}
	return 0;
}

J - Xor-Paths Codeforces 1006F
题意:从左上走到右下,每次只能向右或下走,问走到右下角时路径异或和为k的路径数
直接暴力dfs的话复杂度为240
所以我们用双向dfs 复杂度为2*220=221
用map记录路径异或和
从左上跑一半,右下跑一半
跑到相同点时将答案传回
先贴出我的DFS代码,显然超时了

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

int G[21][21];
int n, m, k, ans;

void dfs(int x, int y, int xorSum) {
	if(x == n && y == m) {
		if(xorSum == k) {
			ans++;
		}
		return;
	}
	if((x + 1) <= n && y <= m) {
		dfs(x + 1, y, xorSum ^ G[x + 1][y]);
	}
	if(x <= n && (y + 1) <= m) {
		dfs(x, y + 1, xorSum ^ G[x][y + 1]);	
	}
}

int main() {
	//freopen("input.txt", "r", stdin);
	scanf("%d %d %d", &n, &m, &k);
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++) {
			scanf("%d", &G[i][j]);
		}
	}
	dfs(1, 1, G[1][1]);
	printf("%d\n", ans);
	//fclose(stdin);
	return 0;
}

下面是正解

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
int n,m;
ll k;
ll a[25][25];
map<ll,ll> dp[25];
void dfs(int x,int y,ll s)
{
    if (x>n||y>m) return;
    if ((x+y)==(n+m)/2+1) {dp[x][s^a[x][y]]++;return;}
    dfs(x+1,y,s^a[x][y]);dfs(x,y+1,s^a[x][y]);
}
ll solve(int x,int y,ll s)
{
    if (x<1||y<1) return 0;
    if ((x+y)==(n+m)/2+1) return dp[x][s];
    return solve(x-1,y,s^a[x][y])+solve(x,y-1,s^a[x][y]);
}
int main()
{
    scanf("%d%d%I64d",&n,&m,&k);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            scanf("%I64d",&a[i][j]);
    dfs(1,1,0);
    printf("%I64d\n",solve(n,m,k));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/AngryDog1024/article/details/82772640