Loading

痛苦的数据结构OJ续

数据结构的OJ题目为什么更新这么频繁。。。。

下面的代码有我写的,有搜索之后修改的,。。。但是这么难的题,大部分都还是修改的(那些代码超级长的题)。

Let the Balloon Rise

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
struct node {
	char x;
	int i;
};
bool operator<(node a, node b) {
	return a.x > b.x;
}
class Set{
private:
	char s[1050][30];
	char n;
	int num[1050];
public:
	Set() {
		for (int i = 0; i < 1050; i++) {
			strcpy(s[i], "");
			num[i] = 0;
		}
		n = 0;
	}
	int find(char *name) {
		for (int i = 0; i < n; i++) 
			if (! strcmp(s[i], name))
				return i;
		return -1;
	}
	void insert(char *name) {
		int i = find(name);
		if (i >= 0) 
			num[i]++;
		else 
			strcpy(s[n++], name);
	}
	void show() {
		int max = 0;
		priority_queue<node> q;
		node x;
		for (int i = 0; i < n; i++) {
			if (max < num[i]) {
				max = num[i];
				while (! q.empty()) {
					q.pop();
				}
				x.x = s[i][0];
				x.i = i;
				q.push(x);
			} else if (max == num[i]){
				x.x = s[i][0];
				x.i = i;
				q.push(x);
			}
		}
		while (! q.empty()) {
			cout << s[q.top().i] << endl;
			q.pop();
		}
	}
};
int main() {
	int n;
	char name[30];
	while ((cin >> n) && n) {
		Set s;
		while (n--) {
			cin >> name;
			s.insert(name);
		}
		s.show();
	}
	return 0;
}

Elevator

#include <iostream>  
using namespace std;  
int main()  
{  
    int x[10000]={0},t,m;  
    while(cin>>m)  
    {  
        if(m!=0)  
        {  
            t=0;  
            for(int i=1;i<=m;i++)  
            {  
                cin>>x[i];  
                if(x[i-1]<x[i])  
                {  
                    t+=(x[i]-x[i-1])*6;  
                }  
                if(x[i-1]>x[i])  
                {  
                    t+=(x[i-1]-x[i])*4;  
                }  
                t+=5;  
            }  
            cout<<t<<endl;  
        }
        else 
            break;
    }
    return 0;
}

彩色字符串

#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
int fun(char x) {
	if (x == '(')
		return 1;
	if (x == '<')
		return 2;
	if (x == '[')
		return 3;
	if (x == ']' || x == ')' || x == '>')
		return -1;
	return 0;
}
int ans[5];
int main() {
	int n,idx;
	char x;
	cin >> n;
	getchar();
	while (n--) {
		stack<char> s;
		ans[1] = ans[2] = ans[3] = 0;
		while (1) {
			x = getchar();
			if (x == '\n') {
				cout << ans[1] << " " << ans[2] << " " << ans[3] << endl;
				break;
			}
			if (! fun(x))
				ans[idx]++;
			else if (fun(x) > 0) {
				s.push(x);
				idx = fun(x);
			}else {
				s.pop();
				if (! s.empty())
					idx = fun(s.top());
				else
					idx = 0;
			}
		}
	}
	return 0;
}

愚人节的礼物

#include <iostream>
using namespace std;
int main(){
	char a[1010];
	while (cin>>a) {
		int i=0;
		int num=0;
		while (a[i]!='\0') {
			if (a[i]=='(') {
				num++;
			}else if(a[i]==')'){
				num--;
			}else{
				cout<<num<<endl;
				break;
			}
			i++;
		}
	}
	return 0;
}

迷宫

#include<string.h>  
#include<ctype.h>  
#include<malloc.h>   
#include<limits.h>
#include<stdio.h>
#include<stdlib.h>  
#define TRUE 1  
#define FALSE 0  
#define OK 1  
#define ERROR 0  
#define INFEASIBLE -1  
#define OVERFLOW 0  
typedef int Status; 
typedef int Boolean; 
#define MAXLENGTH 25  
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2 
typedef struct  
{  
    int r, c;
} PosType;
typedef struct  
{  
    int ord;
    PosType seat;
    int di;  
} SElemType;
typedef struct  
{  
    SElemType * base; 
    SElemType * top;
    int stacksize;
} SqStack;
typedef struct  
{  
    char arr[10][11];  
} MazeType;
Status Pass(MazeType MyMaze, PosType CurPos)  
{  
    if (MyMaze.arr[CurPos.r][CurPos.c]==' ' || MyMaze.arr[CurPos.r][CurPos.c]=='S' || MyMaze.arr[CurPos.r][CurPos.c]=='E')  
        return 1;
    else  
        return 0; 
}
void FootPrint(MazeType &MyMaze, PosType CurPos)  
{  
    MyMaze.arr[CurPos.r][CurPos.c] = '*';  
}
PosType NextPos(PosType CurPos, int Dir)  
{  
    PosType ReturnPos;  
    switch (Dir)  
    {  
    case 1:  
        ReturnPos.r = CurPos.r;  
        ReturnPos.c = CurPos.c + 1;  
        break;  
    case 2:  
        ReturnPos.r = CurPos.r + 1;  
        ReturnPos.c = CurPos.c;  
        break;  
    case 3:  
        ReturnPos.r = CurPos.r;  
        ReturnPos.c = CurPos.c - 1;  
        break;  
    case 4:  
        ReturnPos.r = CurPos.r - 1;  
        ReturnPos.c = CurPos.c;  
        break;  
    }  
    return ReturnPos;  
}
void MarkPrint(MazeType &MyMaze, PosType CurPos)  
{  
    MyMaze.arr[CurPos.r][CurPos.c] = '!';  
}
Status InitStack(SqStack *S)  
{
    (*S).base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));  
    if(!(*S).base)  
        exit(OVERFLOW);  
    (*S).top=(*S).base;  
    (*S).stacksize=STACK_INIT_SIZE;  
    return OK;  
}  
  
Status Push(SqStack *S,SElemType e)  
{
    if((*S).top-(*S).base>=(*S).stacksize)
    {  
        (*S).base=(SElemType *)realloc((*S).base,((*S).stacksize+STACKINCREMENT)*sizeof(SElemType));  
        if(!(*S).base)  
            exit(OVERFLOW);
        (*S).top=(*S).base+(*S).stacksize;  
        (*S).stacksize+=STACKINCREMENT;  
    }  
    *((*S).top)++=e;  
    return OK;  
}
Status StackEmpty(SqStack S)  
{
    if(S.top==S.base)  
        return TRUE;  
    else  
        return FALSE;  
}  
Status Pop(SqStack *S,SElemType *e)  
{
    if((*S).top==(*S).base)  
        return ERROR;  
    *e=*--(*S).top;  
    return OK;  
}
Status MazePath(MazeType &maze, PosType start, PosType end)  
{
    SqStack S;  
    PosType curpos;  
    int curstep;  
    SElemType e;  
    InitStack(&S);  
    curpos = start;
    curstep = 1;
    do  
    {  
        if (Pass(maze, curpos))
        {  
            FootPrint(maze, curpos);
            e.di = 1;  
            e.ord = curstep;  
            e.seat = curpos;  
            Push(&S, e);
            if (curpos.r == end.r && curpos.c == end.c)  
                return (TRUE);  
            curpos = NextPos(curpos, 1); 
            curstep++; 
        }  
        else  
        {  
            if (!StackEmpty(S))  
            {  
                Pop(&S, &e);  
                while (e.di == 4 && !StackEmpty(S))  
                {  
                    MarkPrint(maze, e.seat);  
                    Pop(&S, &e); 
                }
                if (e.di < 4)  
                {  
                    e.di++;  
                    Push(&S, e);
                    curpos = NextPos(e.seat, e.di);
                } 
            }
        }
    }  
    while (!StackEmpty(S));  
    return FALSE;  
}  
int main()  
{  
    int i, j;  
    PosType start, end; 
    MazeType maze; 
    memset(maze.arr, 0, sizeof(maze.arr)); 
    for(i=0; i<10; i++) 
    {  
        gets(maze.arr[i]);  
        for(j=0; j<10; j++)  
        {  
            if(maze.arr[i][j] == 'S')
            {  
                start.r = i;  
                start.c = j;  
            }  
            else if(maze.arr[i][j] == 'E')
            {  
                end.r = i;  
                end.c = j;  
            }  
        }  
    }  
    MazePath(maze, start, end);
    for(i=0; i<10; i++)
    {  
        puts(maze.arr[i]);  
    }
    return 0;
}

表达式求值

#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int isp(char x) {
	if (x == '#')
		return 0;
	if (x == '(')
		return 1;
	if (x == '*' || x == '/' || x == '%')
		return 5;
	if (x == '+' || x == '-')
		return 3;
	if (x == ')')
		return 6;
}
int icp(char x) {
	if (x == '#') {
		return 0;
	}
	if (x == '(')
		return 6;
	if (x == '*' || x == '/' || x == '%')
		return 4;
	if (x == '+' || x == '-')
		return 2;
	if (x == ')')
		return 1;
}
double fun(double a, double b, char x) {
	if (x == '+')
		return a + b;
	if (x == '-')
		return a - b;
	if (x == '*')
		return a * b;
	if (x == '/')
		return a / b;
}
int main () {
	char x;
	int n = 0;
	stack<char> op;
	stack<double> num;
	op.push('#');
	double a, b;
	queue<int> q;
	while (cin >> x) {
		if (x >= '0' && x <= '9') {
			n = n * 10 + x - '0';
			cin >> x;
			if (! (x >= '0' && x <= '9')) {
				num.push(n);
				n = 0;
			}
			cin.putback(x);
			continue;
		}
		if (icp(x) < isp(op.top())) {
			while (icp(x) < isp(op.top())) {
				b = num.top();
				num.pop();
				a = num.top();
				num.pop();
				num.push(fun(a, b, op.top()));
				op.pop();
			}
		}
		if (icp(x) > isp(op.top())) {
			op.push(x);
		}
		if (x == ')') {
			op.pop();
		}
		if (x == '#') {
			cout << num.top() << endl;
			while (! num.empty()) {
				num.pop();
			}
			while (! op.empty()) {
				op.pop();
			}
			op.push('#');
			n = 0;
		}
	}
	return 0;
}

n阶Hanoi塔问题

#include <iostream>
#include <iomanip>
using namespace std;
char s1[] = {'Y', 'Z'};	
char s2[] = {'X', 'Y'};
void hanoi(int n, char from, char to, char xx, int &i) {
	if (n == 1) {
		cout << setw(2) << i << ". Move disk " << n << " from " << from << " to " << to << endl;
		i++;
		return;
	}
	hanoi(n - 1, from, xx, to, i);
	cout << setw(2) << i << ". Move disk " << n <<" from " << from << " to " << to << endl;
	i++;
	hanoi(n - 1, xx, to, from, i);
}
int main() {
	int n;
	while (cin >> n) {
		int i = 1;
		hanoi(n, 'X', 'Z', 'Y', i);
		cout << endl;
	}
	return 0;
}

定位子串

#include <iostream>
#include <cstring>
using namespace std;
int main() {
	char str1[150], str2[150];
	char *s;
	while (cin >> str1) {
		cin >> str2;
		s = strstr(str1, str2);
		if (s == NULL)
			cout << 0 << endl;
		else
			cout << (s - str1) / sizeof(char) + 1 << endl;
	}
	return 0;
}

字符串插入

#include <iostream>
#include <cstring>
using namespace std;
int main() {
	char s1[200], s2[200];
	int n;
	while (cin >> s1 >> s2 >> n) {
		int l1 = strlen(s1);
		int l2 = strlen(s2);
		for (int i = 0; i < n - 1; i++) {
			cout << s1[i]; 
		}
		for (int i = 0; i < l2; i++) {
			cout << s2[i];
		}
		for (int i = n - 1; i < l1; i++) {
			cout << s1[i];
		}
		cout << endl;
	}
	return 0;
}

求子串位置的定位函数

#include <iostream>
#include <cstring>
using namespace std;
int main() {
	char s1[1000],s2[1000];
	while (cin >> s1 >> s2) {
		int i = 0;
		for (; i < strlen(s1); i++) {
			cout << s1[i];
			if (s1[i] == s2[0]) {
				int j = 1;
				for (; j < strlen(s2); j++) {
					if (i + j < strlen(s1))
						cout << s1[i + j];
					if (i + j >= strlen(s1) || s1[i + j] != s2[j])
						break;
				}
				if (j == strlen(s2)) {
					cout << endl << i + 1 << endl;
					break;
				}
			}
		}
		if (i == strlen(s1)) {
			cout << endl << 0 << endl;
		}
	}
	return 0;
}

KMP算法中的模式串移动数组

#include <iostream>
#include <cstring>
using namespace std;
void get_next(char *t, int *next) {
	int i = 1;
	next[1] = 0;
	int j = 0;
	while (i < t[0]) {
		if (j == 0 || t[i] == t[j]) {
			++i;
			++j;
			next[i] = j;
		}else
			j = next[j];
	}
}
int main() {
	char s[105],t[105];
	while (cin>>s){
		t[0]=strlen(s);
		strcpy(t+1,s);
		int next[1000];
		get_next(t,next);
		for (int i=1;i<=t[0];i++) {
			cout<<next[i]<< " ";
		}
		cout<<endl;
	}
	return 0;
}

KMP字符串模式匹配算法实现

#include <iostream>
#include <cstring>
using namespace std;
class SString{
private:
	char *s;
	char len;
public:
	SString(char *ss) {
		set(ss);
	}
	void set(char *ss) {
		s = ss;
		len = strlen(s);
	}
	char& operator[](int index) {
		if (index == 0) {
			return len;
		}
		return s[index - 1];
	}
};
void get_next(SString t, int *next) {
	int i = 1;
	next[1] = 0;
	int j = 0;
	while (i < t[0]) {
		if (j == 0 || t[i] == t[j]) {
			++i;
			++j;
			next[i] = j;
		}else
			j = next[j];
	}
}
int Index_KMP(SString S, SString T, int pos) {
	int next[255];
	int i = pos;
	int j = 1;
	get_next(T, next);
	while (i <= S[0] && j <= T[0]) {
		if (j == 0 || S[i] == T[j]) {
			++i;
			++j;
		}else {
			j = next[j];
		}
	}
	if (j > T[0])
		return i - T[0];
	else
		return 0;
}
int main() {
	char s1[105], s2[105];
	while (cin >> s1 >> s2) {
		cout << Index_KMP(SString(s1), SString(s2), 1) << endl;
	}
	return 0;
}

稀疏矩阵转置

#include <iostream>
#include <iomanip>
using namespace std;
template<class T>
struct Trituple
{
    int row;
    int col;
    T val;
};
template<class T>
class SparseMatrix
{
public:
    SparseMatrix(int maxt=100);
    ~SparseMatrix();
    bool TransposeTo(SparseMatrix &);
    bool AddTo(const SparseMatrix&);
    void Input();
    void Output();
private:
    Trituple<T>* data;
    int rows,cols,terms;
    int maxterms;
};
template<class T>
SparseMatrix<T>::SparseMatrix(int maxt)
{
    maxterms=maxt;
    data=new Trituple<T>[maxterms];
    terms=rows=cols=0;
}
template<class T>
SparseMatrix<T>::~SparseMatrix()
{
    if (data!=NULL)
    {
        delete[] data;
    }
}
template<class T>
bool SparseMatrix<T>::TransposeTo(SparseMatrix &B)
{
    if (terms>B.maxterms)
    {
        return false;
    }
    B.rows=cols;
    B.cols=rows;
    B.terms=terms;
    if (terms>0)
    {
        int p=0;
        for (int j=1;j<=cols;j++)
        {
            for (int k=0;k<terms;k++)
            {
                if (data[k].col==j)
                {
                    B.data[p].row=j;
                    B.data[p].col=data[k].row;
                    B.data[p].val=data[k].val;
                    p++;
                }
            }
        }
    }
    return true;
}
template<class T>
void SparseMatrix<T>::Input()
{
    int row1,col1,number;
    cin>>row1>>col1;
    rows=row1;
    cols=col1;
    for (int i=0;i<rows;i++)
    {
        for (int j=0;j<cols;j++)
        {
            cin>>number;
            if (number!=0)
            {
                data[terms].row=i+1;
                data[terms].col=j+1;
                data[terms].val=number;
                terms++;
            }
        }
    }
}
template<class T>
void SparseMatrix<T>::Output()
{
    T **tempArray=new T*[rows];
    for (int i1=0;i1<rows;i1++)
    {
        tempArray[i1]=new int[cols];
    }
    for (int j=0;j<rows;j++)
    {
        for (int k=0;k<cols;k++)
        {
            tempArray[j][k]=0;
        }
    }
    for (int i=0;i<terms;i++)
    {
        tempArray[data[i].row-1][data[i].col-1]=data[i].val;
    }
    for (int j=0;j<rows;j++)
    {
        for (int k=0;k<cols;k++)
        {
            cout<<tempArray[j][k]<<" ";
        }
        cout<<endl;
    }
    for (int l=0;l<rows;l++)
    {
        delete[] tempArray[l];
    }
    delete tempArray;
    cout<<endl;
}
template<class T>
bool SparseMatrix<T>::AddTo(const SparseMatrix& B)
{
    if (rows!=B.rows||cols!=B.cols)
    {
        return false;
    }
    bool flag=false;
    int tempTerms=terms;
    for (int i=0;i<B.terms;i++)
    {
        flag=false;
        for (int j=0;j<tempTerms;j++)
        {
            if (data[j].col==B.data[i].col&&data[j].row==B.data[i].row)
            {
                data[j].val+=B.data[i].val;
                flag=true;
            }
        }
        if (flag==false)
        {
            data[++terms-1].col=B.data[i].col; 
            data[terms-1].row=B.data[i].row;
            data[terms-1].val=B.data[i].val;
        }
    }
    return true;
}
int main()
{
    SparseMatrix<int> sm(50);
    SparseMatrix<int> sm1(50);
    SparseMatrix<int> sm2(50);
    sm.Input();
    sm.TransposeTo(sm1);
    sm1.Output();
    return 0;
}

稀疏矩阵快速转置

这道题我提交了十次才AC。。。。

#include<iostream>
using namespace std;
#define MAXROW 250
#define MAXSIZE 12500
typedef int ElemType;
typedef struct
{
	int i, j;
	ElemType e;
}Triple;
typedef struct
{
	Triple data[MAXSIZE + 1];
	int n, m, t;
}Matrix;
void Inst(Matrix &a)
{
	int i, j;
	ElemType tmp;
	cin>>a.n>>a.m;
	a.t = 0;
	for (i = 1; i <= a.n; i++)
	{
		for (j = 1; j <= a.m; j++)
		{
			cin>>tmp;
			if (tmp)
			{
				a.t++;
				a.data[a.t].i = i;
				a.data[a.t].j = j;
				a.data[a.t].e = tmp;
			}
		}
	}
}
void Trans(Matrix a, Matrix &b)
{
	int num[MAXROW + 1] = { 0 }, pos[MAXROW + 1] = { 0 };
	int i, j, p;
	b.n = a.m; b.m = a.n; b.t = a.t;
	for (i = 1; i <= a.t; i++) num[a.data[i].j]++;
	for (i = 1; i <= a.m; i++) pos[i] = pos[i - 1] + num[i];
	for (i = a.t; i >= 1; i--)
	{
		p = pos[a.data[i].j]--;
		b.data[p].i = a.data[i].j;
		b.data[p].j = a.data[i].i;
		b.data[p].e = a.data[i].e;
	}
}
void Out(Matrix a)
{
	int i, j;
	int u = 1;
	for (i = 1; i <= a.n; i++)
	{
		for (j = 1; j <= a.m; j++)
		if (i == a.data[u].i && j == a.data[u].j)
			cout<<a.data[u++].e<<" ";
		else
			cout<<"0"<<" ";
		cout<<endl;
	}
}
int main()
{
	Matrix a, b;
	Inst(a);
	Trans(a, b);
	Out(b);
	return 0;
}
posted @ 2017-05-27 00:58  bay1  阅读(160)  评论(0编辑  收藏  举报